mYs*_*elf 6 bash gnu sed gnome-terminal
我可以使用以下示例执行此操作.所述第一命令将输出线16 ... 80从file1到patch,而第二将插入的内容patch线18后file2:
sed -n 16,80p file1>patch
sed -i 18rpatch file2
Run Code Online (Sandbox Code Playgroud)
但是,我想直接从一个文件复制到另一个文件而不使用中间的临时文件,在一个命令中使用sed(不是awk等).我很确定这是可能的,只是不知道如何.
使用sed执行此操作需要一些额外的shell技巧.假设bash,你可以使用
sed -i 18r<(sed '16,80!d' file1) file2
Run Code Online (Sandbox Code Playgroud)
在哪里<(sed '16,80!d' file1)用sed '16,80!d' file1可以读取输出的管道名称替换.
一般来说,我觉得用awk做这个更好(如果再长一点),因为awk能更好地处理多个输入文件.例如:
awk 'NR == FNR { if(FNR >= 16 && FNR <= 80) { patch = patch $0 ORS }; next } FNR == 18 { $0 = patch $0 } 1' file1 file2
Run Code Online (Sandbox Code Playgroud)
其工作原理如下:
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.
Run Code Online (Sandbox Code Playgroud)
但是,这种方法不适合文件的就地编辑.这通常不是问题; 我只是用
cp file2 file2~
awk ... file1 file2~ > file2
Run Code Online (Sandbox Code Playgroud)
如果事情变成梨形,还有额外的备份优势,但最终还是取决于你.