SED:将一个文件中的行复制到另一个文件中的特定行 [英] SED: copy lines from a file to specific line in another file
本文介绍了SED:将一个文件中的行复制到另一个文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用下面的示例来实现这一点。第一个命令将输出从file1
到patch
的16...80行,而第二个命令将在第18行之后将patch
的内容插入到file2
:
sed -n 16,80p file1>patch
sed -i 18rpatch file2
但是,我希望在一个命令中使用sed(而不是awk等)直接从一个文件复制到另一个文件,而不是使用中间的临时文件。我很确定这是可能的,只是不知道怎么做。
推荐答案
使用sed执行此操作需要一些额外的外壳技巧。假设bash,您可以使用
sed -i 18r<(sed '16,80!d' file1) file2
其中<(sed '16,80!d' file1)
替换为可从中读取sed '16,80!d' file1
输出的管道的名称。
awk 'NR == FNR { if(FNR >= 16 && FNR <= 80) { patch = patch $0 ORS }; next } FNR == 18 { $0 = patch $0 } 1' file1 file2
其工作原理如下:
NR == FNR { # While processing the first file
if(FNR >= 16 && FNR <= 80) { # remember the patch lines
patch = patch $0 ORS
}
next # and do nothing else
}
FNR == 18 { # after that, while processing the first file:
$0 = patch $0 # prepend the patch to line 18
}
1 # and print regardless of whether the current
# line was patched.
但是,这种方法不适合就地编辑文件。这通常不是问题;我只需使用
cp file2 file2~
awk ... file1 file2~ > file2
还有一个额外的优势,那就是有一个备份,以防事情变得糟糕,但最终还是要由您来决定。
这篇关于SED:将一个文件中的行复制到另一个文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文