Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
share|improve this question
    
    
or this superuser.com/questions/162133/… –  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
add comment

2 Answers

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
1  
@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
add comment

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

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

Your Answer

 
discard

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.