Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing from match to end-of-line

Tags:

regex

sed

This should be incredibly easy but I can't get it to work. I just want to use sed to replace from one string to the end of a line. For example if I have the following data file:

   one  two  three  five    four two  five five six    six  one  two seven four 

and I want to replace from the word "two" through the end of the line with the word "BLAH" ending up with the output:

   one BLAH    four BLAH    six one BLAH 

wouldn't that just be:

   sed -e 's/two,$/BLAH/g' 

I'm not the best at regex to maybe that's the problem

like image 616
GregH Avatar asked Feb 18 '11 22:02

GregH


People also ask

How can I replace text after a specific word using sed?

The following `sed` command shows the use of 'c' to replace everything after the match. Here, 'c' indicates the change. The command will search the word 'present' in the file and replace everything of the line with the text, 'This line is replaced' if the word exists in any line of the file.


2 Answers

This should do what you want:

sed 's/two.*/BLAH/'

$ echo "   one  two  three  five >    four two  five five six >    six  one  two seven four" | sed 's/two.*/BLAH/'    one  BLAH    four BLAH    six  one  BLAH 

The $ is unnecessary because the .* will finish at the end of the line anyways, and the g at the end is unnecessary because your first match will be the first two to the end of the line.

like image 113
Andrew Clark Avatar answered Sep 20 '22 15:09

Andrew Clark


Use this, two<anything any number of times><end of line>

's/two.*$/BLAH/g' 
like image 26
Erik Avatar answered Sep 23 '22 15:09

Erik