Skip to main content
 首页 » 编程设计

python之在文件中的每一行之后添加额外的行

2025年05月04日12qq号

在文件中的每一行之后添加额外的行

我需要有关大约 1000 行文件的以下任务的帮助。

输入

    ./create.pl     1eaj.out 
    ./create.pl     1ezg.out 
    ./create.pl     1f41.out 
    ... 

输出

    ./create.pl     1eaj.out 
    mv complex.* 1eaj 
    ./create.pl     1ezg.out 
    mv complex.* 1ezg 
    ./create.pl     1f41.out 
    mv complex.* 1f41 
    ... 

我知道下面的命令可以添加新行和第一部分,这使得输出如下。

    awk ' {print;} NR % 1 == 0 { print "mv complex.*  "; }' 
 
    ./create.pl     1eaj.out 
    mv complex.*  
    ./create.pl     1ezg.out 
    mv complex.*  
    ./create.pl     1f41.out 
    mv complex.*  
    ... 

剩下的怎么办? 非常感谢。

请您参考如下方法:

我的尝试:

sed -n 's/^\(\.\/create\.pl\)\s*\(.*\)\.out$/\1 \2.out\nmv complex.* \2/p' s.txt 

或在 ./create.pl 和 mv 之间使用 &&(因为 mv 可能仅在 ./create. pl 被正确执行):

sed -n 's/^\(\.\/create\.pl\)\s*\(.*\)\.out$/\1 \2.out \&\& mv complex.* \2/p' s.txt 

给出:

./create.pl 1eaj.out && mv complex.* 1eaj 
./create.pl 1ezg.out && mv complex.* 1ezg 
./create.pl 1f41.out && mv complex.* 1f41