This question already has an answer here:
这个问题在这里已有答案:
- Delete lines in a text file that contain a specific string 14 answers
- 删除文本文件中包含特定字符串14个答案的行
I want to delete a line containing a specific string from the file. How can I do this without using awk
? I tried to use sed
but I could not achieve it.
我想从文件中删除包含特定字符串的行。如何在不使用awk的情况下执行此操作?我试图使用sed但我无法实现它。
3 个解决方案
#1
32
This should do it:
这应该这样做:
sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *
it will replace all occurrences of "deletethis" with "" (nothing) in all files (*
), editing them in place.
它将在所有文件(*)中用“”(无)替换所有出现的“deletethis”,并在适当的位置进行编辑。
In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".
在第二种形式中,模式可以编辑得更安全一些,并且通过用“.backup”后缀来备份任何修改过的文件。
The third form is the way some versions of sed
like it. (e.g. Mac OS X)
第三种形式是某些版本的sed喜欢它的方式。 (例如Mac OS X)
man sed
for more information.
男子sed获取更多信息。
#2
16
sed -i '/pattern/d' file
Use 'd' to delete a line. This works at least with GNU-Sed.
使用“d”删除一行。这至少适用于GNU-Sed。
If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:
如果您的Sed没有选项,要更改文件,也许您可以使用中间文件来存储修改:
sed '/pattern/d' file > tmpfile && mv tmpfile file
Writing directly to the source usually doesn't work: sed '/pattern/d' file > file
so make a copy before trying out, if you doubt it.
直接写入源代码通常不起作用:sed'/ pattern / d'file>文件,所以如果你有疑问,请在试用之前复制一份。
#3
0
Try the vim-way:
试试vim-way:
ex -s +"g/foo/d" -cwq file.txt
#1
32
This should do it:
这应该这样做:
sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *
it will replace all occurrences of "deletethis" with "" (nothing) in all files (*
), editing them in place.
它将在所有文件(*)中用“”(无)替换所有出现的“deletethis”,并在适当的位置进行编辑。
In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".
在第二种形式中,模式可以编辑得更安全一些,并且通过用“.backup”后缀来备份任何修改过的文件。
The third form is the way some versions of sed
like it. (e.g. Mac OS X)
第三种形式是某些版本的sed喜欢它的方式。 (例如Mac OS X)
man sed
for more information.
男子sed获取更多信息。
#2
16
sed -i '/pattern/d' file
Use 'd' to delete a line. This works at least with GNU-Sed.
使用“d”删除一行。这至少适用于GNU-Sed。
If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:
如果您的Sed没有选项,要更改文件,也许您可以使用中间文件来存储修改:
sed '/pattern/d' file > tmpfile && mv tmpfile file
Writing directly to the source usually doesn't work: sed '/pattern/d' file > file
so make a copy before trying out, if you doubt it.
直接写入源代码通常不起作用:sed'/ pattern / d'file>文件,所以如果你有疑问,请在试用之前复制一份。
#3
0
Try the vim-way:
试试vim-way:
ex -s +"g/foo/d" -cwq file.txt