在shell脚本中的file2中的特定行之后粘贴file1中的一行

时间:2013-09-30 06:37:59

标签: bash shell

我想使用shell脚本在第二个文件中的特定行粘贴一行文件。

我有2个文件 - file1file2。我想从file1粘贴第5行,因此它显示为file2中的第7行,file2中的所有行也出现在输出中。

1 个答案:

答案 0 :(得分:1)

当然,有多种方法可以做到这一点。

awk

awk 'NR == 5 { line5 = $0 }
     FNR != NR { print; if (FNR == 6) print line5 }' file1 file2

NR是超过记录的数字;脚本的第一行在变量file1中保存line5的第5行。读取第二个文件时适用FNR != NR条件;它会打印该行,如果第二个文件中的行号为6,它还会打印line5

sed

sed -f <(sed -e '1,4d; 6,$d; x; s/.*/6a\\/;p; x' file1) file2

这使用bash process substitution。进程替换中的sed脚本删除file1的第1-4和6-EOF行。对于剩余的第5行,它交换模式空间和保持空间,编辑保留空间,使其包含6a\并打印它,然后交换模式空间并再次保持空间,并(隐式)打印原始线。因此,它生成一个脚本,如:

6a\
All important line 5

这是提供给第二个(外部)sed,它会在file1的第6行之后从file2添加第5行。

file1

Garbage line 1
Garbage line 2
Garbage line 3
Garbage line 4
All important line 5
Garbage line 6
Garbage line 7
Garbage line 8
Garbage line 9

file2

This is line 1 in file2
This is line 2 in file2
This is line 3 in file2
This is line 4 in file2
This is line 5 in file2
This is line 6 in file2
This is line 7 in file2
This is line 8 in file2
This is line 9 in file2

输出

This is line 1 in file2
This is line 2 in file2
This is line 3 in file2
This is line 4 in file2
This is line 5 in file2
This is line 6 in file2
All important line 5
This is line 7 in file2
This is line 8 in file2
This is line 9 in file2