Insert linefeed in sed (Mac OS X)

前端 未结 9 1021
长情又很酷
长情又很酷 2020-11-29 01:36

How do I insert a newline in the replacement part of sed?

This code isn\'t working:

sed \"s/\\(1234\\)/\\n\\1/g\" input.txt > output.txt
         


        
9条回答
  •  误落风尘
    2020-11-29 01:52

    Unfortunately, for me, sed seems to ignore \ns in the replacement string.

    $ echo test1234foo123bar1234 | sed "s/\(1234\)/\n\1/g"
    testn1234foo123barn1234
    

    If that happens for you as well, an alternative is to use:

    $ echo test1234foo123bar1234 | sed "s/\(1234\)/\\`echo -e '\n\r'`\1/g"
    

    This should work anywhere and will produce:

    test
    1234foo123bar
    1234
    

    For your example with an input.txt file as input and output.txt as output, use:

    $ sed "s/\(1234\)/\\`echo -e '\n\r'`\1/g" input.txt > output.txt
    

提交回复
热议问题