我有一个文本文件,我想删除包含单词的所有行:facebook,youtube,google,amazon,dropbox,等.
我知道用sed删除包含字符串的行:
sed '/facebook/d' myfile.txt
Run Code Online (Sandbox Code Playgroud)
我不想为每个字符串运行此命令五次,但有没有办法将所有字符串组合成一个命令?
试试这个:
sed '/facebook\|youtube\|google\|amazon\|dropbox/d' myfile.txt
Run Code Online (Sandbox Code Playgroud)
regexp1\|regexp2匹配
regexp1或者regexp2.使用括号来使用复杂的替代正则表达式.匹配过程依次从左到右尝试每个替代,并使用成功的第一个替代.它是GNU扩展.
grep -vf wordsToExcludeFile myfile.txt
Run Code Online (Sandbox Code Playgroud)
"wordsToExcludeFile"应包含您不想要的单词,每行一个.
如果需要将结果保存回同一文件,请将其添加到命令中:
> myfile.new && mv myfile.new myfile.txt
Run Code Online (Sandbox Code Playgroud)
和 awk
awk '!/facebook|youtube|google|amazon|dropbox/' myfile.txt > filtered.txt
Run Code Online (Sandbox Code Playgroud)