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
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
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.
content of a sample file.txt
$ cat file.txt
WORD1 WORD2 WORD3
WORD4 WORD5 WORD6
WORD7 WORD8 WORD9
(Correction by @DennisWilliamson in comment)
$ sed -e 's/\([^ ]\+\) \+\([^ ]\+\) \+\(.*\)/\1 foo \3/' file.txt
WORD1 foo WORD3
WORD4 foo WORD6
WORD7 foo WORD9
while awk
is somehow simpler
$ awk -F' ' '{ print $1" foo "$3 }' file.txt
WORD1 foo WORD3
WORD4 foo WORD6
WORD7 foo WORD9