如何使用sed删除文本文件中包含特定字符串的所有行?


当前回答

SED:

'James \| John/d'-詹姆斯/约翰/!“p”

AWK:

'!/詹姆斯|约翰/'/James | John/{next;}{print}

GREP(语法):

-v“詹姆斯·约翰”

其他回答

我用一个包含大约345000行的文件制作了一个小型基准测试。在这种情况下,使用grep的方法似乎比sed方法快15倍左右。

我已经尝试了使用和不使用设置LC_ALL=C,这似乎不会显著改变定时。搜索字符串(CDGA_00004.pdbqt.gz.tar)位于文件的中间位置。

以下是命令和计时:

time sed -i "/CDGA_00004.pdbqt.gz.tar/d" /tmp/input.txt

real    0m0.711s
user    0m0.179s
sys     0m0.530s

time perl -ni -e 'print unless /CDGA_00004.pdbqt.gz.tar/' /tmp/input.txt

real    0m0.105s
user    0m0.088s
sys     0m0.016s

time (grep -v CDGA_00004.pdbqt.gz.tar /tmp/input.txt > /tmp/input.tmp; mv /tmp/input.tmp /tmp/input.txt )

real    0m0.046s
user    0m0.014s
sys     0m0.019s

您也可以使用此选项:

 grep -v 'pattern' filename

这里,-v将只打印图案以外的图案(这意味着反转匹配)。

如果有人想对字符串进行精确匹配,您可以使用grep-w中的-w标志来表示整数。也就是说,例如,如果要删除编号为11的行,但保留编号为111的行:

-bash-4.1$ head file
1
11
111

-bash-4.1$ grep -v "11" file
1

-bash-4.1$ grep -w -v "11" file
1
111

如果您想同时排除几个确切的模式,它也可以使用-f标志。如果“黑名单”是要从“文件”中删除的每一行都有多个模式的文件:

grep -w -v -f blacklist file

除了sed之外,还有许多其他方法可以删除具有特定字符串的行:

AWK

awk '!/pattern/' file > temp && mv temp file

红宝石(1.9+)

ruby -i.bak -ne 'print if not /test/' file

Perl

perl -ni.bak -e "print unless /pattern/" file

Shell(bash 3.2及更高版本)

while read -r line
do
  [[ ! $line =~ pattern ]] && echo "$line"
done <file > o
mv o file

GNU grep

grep -v "pattern" file > temp && mv temp file

当然,sed(打印相反内容比实际删除更快):

sed -n '/pattern/!p' file

SED:

'James \| John/d'-詹姆斯/约翰/!“p”

AWK:

'!/詹姆斯|约翰/'/James | John/{next;}{print}

GREP(语法):

-v“詹姆斯·约翰”