Insert linefeed in sed (Mac OS X)

前端 未结 9 964
长情又很酷
长情又很酷 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:58

    The newline in the middle of the command can feel a bit clumsy:

    $ echo abc | sed 's/b/\
    /'
    a
    c
    

    Here are two solutions to this problem which I think should be quite portable (should work for any POSIX-compliant sh, printf, and sed):

    Solution 1:

    Remember to escape any \ and % characters for printf here:

    $ echo abc | sed "$(printf 's/b/\\\n/')"
    a
    c
    

    To avoid the need for escaping \ and % characters for printf:

    $ echo abc | sed "$(printf '%s\n%s' 's/b/\' '/')"
    a
    c
    

    Solution 2:

    Make a variable containing a newline like this:

    newline="$(printf '\nx')"; newline="${newline%x}"
    

    Or like this:

    newline='
    '
    

    Then use it like this:

    $ echo abc | sed "s/b/\\${newline}/"
    a
    c
    

提交回复
热议问题