Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a unknown string between two known strings with sed

Tags:

regex

bash

sed

I have a file with the following contents:

WORD1 WORD2 WORD3

How can I use sed to replace the string between WORD1 and WORD3 with foo, such that the contents of the file are changed to the following?:

WORD1 foo WORD3

I tried the following, but obviously I'm missing something because that does not produce the desired results:

sed -i '' 's/WORD1.*WORD3/foo/g' file.txt

like image 951
Camden S. Avatar asked May 16 '12 07:05

Camden S.


People also ask

How do you substitute a string with sed?

Find and replace text within a file using sed command The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

How do you use sed to replace the first occurrence in a file?

With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.

How do you sed a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.


2 Answers

sed -i 's/WORD1.*WORD3/WORD1 foo WORD3/g' file.txt 

or

sed -i 's/(WORD1).*(WORD3)/\1 foo \2/g' file.txt 

You might need to escape round brackets, depends on your sed variant.

like image 160
vyegorov Avatar answered Sep 19 '22 12:09

vyegorov


This might work for you:

sed 's/\S\+/foo/2' file 

or perhaps:

sed 's/[^[:space:]][^[:space:]]*/foo/2' file 

If WORD1 and WORD3 occur more than once:

echo "WORD1 WORD2 WORD3 BLA BLA WORD1 WORD4 WORD3" | sed 's/WORD3/\n&/g;s/\(WORD1\)[^\n]*\n/\1 foo /g' WORD1 foo WORD3 BLA BLA WORD1 foo WORD3 
like image 34
potong Avatar answered Sep 19 '22 12:09

potong