将与模式匹配的行从一个文件移动到另一个文件 [英] Move lines matching a pattern from one file to another
问题描述
我想将符合特定模式的行从 file1 移到 file2 .类似于操作在Windows中将一个文件剪切并粘贴到另一个文件
I want to move lines matching certain pattern from file1 to file2. Analogous to operation cut and paste from one file to another in windows
示例
假设我要从 file1 中删除所有包含bar
的行并将其粘贴到新创建的 file2
let's say I want to cut all lines containg bar
from file1 and paste it into newly created file2
输入:
file1
bla foo bla
bla bar bla
bla aaa bla
bla bar bla
bla foo bla
处理后所需的输出:
file1
bla foo bla
bla aaa bla
bla foo bla
file2
bla bar bla
bla bar bla
我尝试过的事情
grep
创建所需的 file2 ,但不修改 file1
grep
creates desired file2 but doesn't modify file1
grep 'bar' file1 > file2
sed -i
修改所需的 file1 ,但不创建 file2
sed -i
modifies desired file1 but doesn't create file2
sed -i '/bar/d' file1
如果我一个接一个地执行这两个命令,则会得到理想的结果.但是在这里,出于好奇,我正在寻找单行命令,并使脚本更简洁.
If I execute both commands one after another, I get desired result. But here I am looking for a single line command out of curiosity and to make a script more concise.
您的帮助将不胜感激.
推荐答案
这可能对您有用(GNU sed):
This might work for you (GNU sed):
sed -i -e '/bar/{w file2' -e 'd}' file1
替代方法:
sed -i -e '/bar/w file2' -e '//d' file1
要追加到file2,请写入一个临时文件,然后使用bash脚本中的cat追加到文件的末尾,或者使用:
To append to file2, write to a temporary file and use cat to append at the end of file in a bash script, or use:
sed -i -e '/bar/w tmpfile' -e '$e cat tmpfile >> file2 && rm tmpfile' -e '//d' file1
对于最后一种解决方案,一次只能修改一个输入文件.
N.B. For the last solution, only one input file can be modified at a time.
这篇关于将与模式匹配的行从一个文件移动到另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!