Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


I'm searching for 'mystring'

File contains:

foo bar mystring bar foo

I'm trying to get to:

foo bar
share|improve this question
or this… – Paul Jun 28 '12 at 13:54
> and replace everything afterwards (including the search string) with a blank string … what do you mean by afterwards? Everything following in that line? – slhck Jun 28 '12 at 13:56
@Dennis Looks like I may have misunderstood the requirement here, so lets wait and see what the OP says – Paul Jun 28 '12 at 14:00
up vote 4 down vote accepted
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.

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

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

perl -p -i -e 's/mystring.*//' *.ext
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.