replace a unknown string between two known strings with sed

后端 未结 3 1593
广开言路
广开言路 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:38

    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
    

提交回复
热议问题