我想使用shell脚本在第二个文件中的特定行粘贴一行文件。
我有2个文件 - file1
和file2
。我想从file1
粘贴第5行,因此它显示为file2
中的第7行,file2
中的所有行也出现在输出中。
答案 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