如何读取文件 A 中的每一行/字符串,并在文件 B 中找到包含该字符串的行并将其删除到 ubuntu
How to read in each line/ string in a file A, and find the line containing the string in file B and deltes it in ubuntu
我知道如何在文件中搜索字符串,并使用 sed 删除包含该字符串的行。
sed -i '/pattern/d' ./file
但是我需要找到很多字符串,有没有办法自动执行此操作?例如,从文件 A 中逐行读取字符串,并将其作为变量传递给 sed,以便 sed 可以找到包含该字符串的行并将其删除?
谢谢。
您可以将命令替换与 sed
的 -f
:
结合使用
$ cat file
one two foo
bar three four
qux
quux
blah
blupp
$ cat exclude
foo
bar
^qu
$ sed -i -f <(sed 's#\(.*\)#//d#g' exclude) file
$ cat file
blah
blupp
但这不是很可靠,除非您知道您的模式不会包含 sed
解释的字符。
更好:只需将 grep
与临时文件一起使用:
$ grep -vf exclude file > file.new && mv file.new file
$ cat file
blah
blupp
您可以使用 grep
完成此操作。
有关详细信息,请参阅 man grep
(查找 -v
和 -f
选项)
样本:
$ cat File1
Line with pattern1
Line with jskjdksdjk
Line with ioweuwue
Line with pattern2
Line with sydsudsd
$ cat File2
pattern1
pattern2
$ grep -vf File2 File1
Line with jskjdksdjk
Line with ioweuwue
Line with sydsudsd
替换同一个文件(File1
),grep -vf File2 File1 > tmp && mv tmp File1
我知道如何在文件中搜索字符串,并使用 sed 删除包含该字符串的行。
sed -i '/pattern/d' ./file
但是我需要找到很多字符串,有没有办法自动执行此操作?例如,从文件 A 中逐行读取字符串,并将其作为变量传递给 sed,以便 sed 可以找到包含该字符串的行并将其删除?
谢谢。
您可以将命令替换与 sed
的 -f
:
$ cat file
one two foo
bar three four
qux
quux
blah
blupp
$ cat exclude
foo
bar
^qu
$ sed -i -f <(sed 's#\(.*\)#//d#g' exclude) file
$ cat file
blah
blupp
但这不是很可靠,除非您知道您的模式不会包含 sed
解释的字符。
更好:只需将 grep
与临时文件一起使用:
$ grep -vf exclude file > file.new && mv file.new file
$ cat file
blah
blupp
您可以使用 grep
完成此操作。
有关详细信息,请参阅 man grep
(查找 -v
和 -f
选项)
样本:
$ cat File1
Line with pattern1
Line with jskjdksdjk
Line with ioweuwue
Line with pattern2
Line with sydsudsd
$ cat File2
pattern1
pattern2
$ grep -vf File2 File1
Line with jskjdksdjk
Line with ioweuwue
Line with sydsudsd
替换同一个文件(File1
),grep -vf File2 File1 > tmp && mv tmp File1