0

How can I search for a certain string in multiple files (with a given extension) in a directory and replace everything afterwards (including the search string) with a blank string?


Example

I'm searching for 'mystring'

File contains:

foo bar mystring bar foo

I'm trying to get to:

foo bar
4

2 Answers 2

4
sed -i "s/mystring.*//" <filename>

-i does the replacing inline (i.e. infile == outfile). Without -i the result of the replacing would be printed to stdout.

2
  • 1
    @Dan: To do this in a .txt files (for example), replace <filename> by *.txt. Bash does the rest.
    – Dennis
    Jun 28, 2012 at 14:25
  • +1 for sed because it should already be installed.
    – 에이바
    Jun 28, 2012 at 14:25
2

If you don't need to work on files in subdirectories recursively,

perl -p -i -e 's/mystring.*//' *.ext

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .