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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With