Optimize shell script for multiple sed replacements

前端 未结 7 1892
清歌不尽
清歌不尽 2020-12-19 08:50

I have a file containing a list of replacement pairs (about 100 of them) which are used by sed to replace strings in files.

The pairs go like:



        
7条回答
  •  轮回少年
    2020-12-19 08:55

    { cat replacement_list;echo "-End-"; cat YourFile; } | sed -n '1,/-End-/ s/$/³/;1h;1!H;$ {g
    t again
    :again
       /^-End-³\n/ {s///;b done
          }
       s/^\([^|]*\)|\([^³]*\)³\(\n\)\(.*\)\1/\1|\2³\3\4\2/
       t again
       s/^[^³]*³\n//
       t again
    :done
      p
      }'
    

    More for fun to code via sed. Try maybe for a time perfomance because this start only 1 sed that is recursif.

    for posix sed (so --posix with GNU sed)

    explaination

    • copy replacement list in front of file content with a delimiter (for line with ³ and for list with -End-) for an easier sed handling (hard to use \n in class character in posix sed.
    • place all line in buffer (add the delimiter of line for replacement list and -End- before)
    • if this is -End-³, remove the line and go to final print
    • replace each first pattern (group 1) found in text by second patttern (group 2)
    • if found, restart (t again)
    • remove first line
    • restart process (t again). T is needed because b does not reset the test and next t is always true.

提交回复
热议问题