Replace comma with newline in sed on MacOS?

后端 未结 13 1966
借酒劲吻你
借酒劲吻你 2020-11-27 09:27

I have a file of id\'s that are comma separated. I\'m trying to replace the commas with a new line. I\'ve tried:

sed \'s/,/\\n/g\' file

b

相关标签:
13条回答
  • 2020-11-27 10:07
    sed 's/,/\
    /g'
    

    works on Mac OS X.

    0 讨论(0)
  • 2020-11-27 10:08

    FWIW, the following line works in windows and replaces semicolons in my path variables with a newline. I'm using the tools installed under my git bin directory.

    echo %path% | sed -e $'s/;/\\n/g' | less
    
    0 讨论(0)
  • 2020-11-27 10:12

    Just to clearify: man-page of sed on OSX (10.8; Darwin Kernel Version 12.4.0) says:

    [...]

    Sed Regular Expressions

     The regular expressions used in sed, by default, are basic regular expressions (BREs, see re_format(7) for more information), but extended
     (modern) regular expressions can be used instead if the -E flag is given.  In addition, sed has the following two additions to regular
     expressions:
    
     1.   In a context address, any character other than a backslash (``\'') or newline character may be used to delimit the regular expression.
          Also, putting a backslash character before the delimiting character causes the character to be treated literally.  For example, in the
          context address \xabc\xdefx, the RE delimiter is an ``x'' and the second ``x'' stands for itself, so that the regular expression is
          ``abcxdef''.
    
     2.   The escape sequence \n matches a newline character embedded in the pattern space.  You cannot, however, use a literal newline charac-
          ter in an address or in the substitute command.
    

    [...]

    so I guess one have to use tr - as mentioned above - or the nifty

    sed "s/,/^M
    /g"
    

    note: you have to type <ctrl>-v,<return> to get '^M' in vi editor

    0 讨论(0)
  • 2020-11-27 10:15

    Use an ANSI-C quoted string $'string'

    You need a backslash-escaped literal newline to get to sed. In bash at least, $'' strings will replace \n with a real newline, but then you have to double the backslash that sed will see to escape the newline, e.g.

    echo "a,b" | sed -e $'s/,/\\\n/g'
    

    Note this will not work on all shells, but will work on the most common ones.

    0 讨论(0)
  • 2020-11-27 10:18

    If your sed usage tends to be entirely substitution expressions (as mine tends to be), you can also use perl -pe instead

    $ echo 'foo,bar,baz' | perl -pe 's/,/,\n/g'
    foo,
    bar,
    baz
    
    0 讨论(0)
  • 2020-11-27 10:20

    Use tr instead:

    tr , '\n' < file
    
    0 讨论(0)
提交回复
热议问题