How to replace a multi line string in a bunch files

前端 未结 2 1373
别跟我提以往
别跟我提以往 2021-01-06 14:54
#!/bin/sh
old=\"hello\"
new=\"world\"
sed -i s/\"${old}\"/\"${new}\"/g $(grep \"${old}\" -rl *)

The preceding script just work for single line text

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 15:09

    You could use perl or awk, and change the record separator to something else than newline (so you can match against bigger chunks. For example with awk:

    echo -e "one\ntwo\nthree" | awk 'BEGIN{RS="\n\n"} sub(/two\nthree\n, "foo")'
    

    or with perl (-00 == paragraph buffered mode)

    echo -e "one\ntwo\nthree" | perl -00 -pne 's/two\nthree/foo/'
    

    I don't know if there's a possibility to have no record separator at all (with perl, you could read the whole file first, but then again that's not nice with regards to memory usage)

提交回复
热议问题