Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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.

like image 944
virtue Avatar asked Apr 07 '11 16:04

virtue


People also ask

How do you delete a string from a file?

The replaceAll() method accepts a regular expression and a String as parameters and, matches the contents of the current string with the given regular expression, in case of match, replaces the matched elements with the String. Retrieve the contents of the file as a String.

How do you check if a file exists and then delete in shell script?

@uchuugaka you can do rm -fv and it will output a message if the file was deleted, and it will output nothing if nothing was deleted.

How do you remove a specific line from a file in Unix?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.


1 Answers

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.

like image 55
mvds Avatar answered Sep 24 '22 15:09

mvds