开发者

Search a string in a file and delete it from this file by Shell Script [duplicate]

开发者 https://www.devze.com 2023-02-23 08:05 出处:网络
This question already has answers here: How to delete from a text file, all lines that contain a specific string?
This question already has answers here: How to delete from a text file, all lines that contain a specific string? (21 answers) Closed 5 years ago.

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 ach开发者_JAVA百科ieve it.


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.

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".

The third form is the way some versions of sed like it. (e.g. Mac OS X)

man sed for more information.


sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with 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 '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source doesn't work: sed '/pattern/d' FILE > FILE so make a copy before trying out, if you doubt it. The redirection to a new file FILE will open a new file FILE before reading from it, so reading from it will result in an empty input.


Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt
0

精彩评论

暂无评论...
验证码 换一张
取 消