Delete lines in a text file that contain a specific string

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


To remove the line and print the output to standard out:

sed '/pattern to match/d' ./infile

To directly modify the file:

sed -i '/pattern to match/d' ./infile

To directly modify the file (and create a backup):

sed -i.bak '/pattern to match/d' ./infile

For Mac OS X users:

sed -i '' '/pattern/d' ./infile

there are many other ways to delete lines with specific string besides sed

awk

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

Ruby (1.9+)

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

Perl

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

Shell (bash3.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

and of course sed (printing the inverse is faster than actual deletion. )

sed -n '/pattern/!p' file 

You can use sed to replace lines in place in a file. However, it seems to be much slower than using grep for the inverse into a second file and then moving the second file over the original.

eg

sed -i '/pattern/d' filename      

or

grep -v "pattern" filename > filename2; mv filename2 filename

The first command takes 3 times longer on my machine anyway.

链接地址: http://www.djcxy.com/p/13464.html

上一篇: 在正则表达式之前删除换行符

下一篇: 删除包含特定字符串的文本文件中的行