replace a unknown string between two known strings with sed

后端 未结 3 1591
广开言路
广开言路 2020-11-27 17:53

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

3条回答
  •  长情又很酷
    2020-11-27 18:44

    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
    

提交回复
热议问题