Replace comma with newline in sed on MacOS?

后端 未结 13 1985
借酒劲吻你
借酒劲吻你 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:21

    This works on MacOS Mountain Lion (10.8), Solaris 10 (SunOS 5.10) and RHE Linux (Red Hat Enterprise Linux Server release 5.3, Tikanga)...

    $ sed 's/{pattern}/\^J/g' foo.txt > foo2.txt
    

    ... where the ^J is done by doing ctrl+v+j. Do mind the \ before the ^J.

    PS, I know the sed in RHEL is GNU, the MacOS sed is FreeBSD based, and although I'm not sure about the Solaris sed, I believe this will work pretty much with any sed. YMMV tho'...

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

    To make it complete, this also works:

    echo "a,b" | sed "s/,/\\$(echo -e '\n\r')/"
    
    0 讨论(0)
  • 2020-11-27 10:23

    sed on macOS Mojave was released in 2005, so one solution is to install the gnu-sed,

    brew install gnu-sed
    

    then use gsed will do as you wish,

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

    If you prefer sed, just sudo sh -c 'echo /usr/local/opt/gnu-sed/libexec/gnubin > /etc/paths.d/brew', which is suggested by brew info gnu-sed. Restart your term, then your sed in command line is gsed.

    0 讨论(0)
  • 2020-11-27 10:24
    $ echo $PATH | sed -e $'s/:/\\\n/g' 
    /usr/local/sbin
    /Library/Oracle/instantclient_11_2/sdk
    /usr/local/bin
    

    ...

    Works for me on Mojave

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

    Though I am late to this post, just updating my findings. This answer is only for Mac OS X.

    $ sed 's/new/
    > /g' m1.json > m2.json
    sed: 1: "s/new/
    /g": unescaped newline inside substitute pattern
    

    In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.

    $ sed 's/new/\
    > /g' m1.json > m2.json 
    

    Worked! (in Mac OS X 10.9.3)

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

    Apparently \r is the key!

    $ sed 's/, /\r/g' file3.txt > file4.txt
    

    Transformed this:

    ABFS, AIRM, AMED, BOSC, CALI, ECPG, FRGI, GERN, GTIV, HSON, IQNT, JRCC, LTRE,
    MACK, MIDD, NKTR, NPSP, PME, PTIX, REFR, RSOL, UBNT, UPI, YONG, ZEUS
    

    To this:

    ABFS
    AIRM
    AMED
    BOSC
    CALI
    ECPG
    FRGI
    GERN
    GTIV
    HSON
    IQNT
    JRCC
    LTRE
    MACK
    MIDD
    NKTR
    NPSP
    PME
    PTIX
    REFR
    RSOL
    UBNT
    UPI
    YONG
    ZEUS
    
    0 讨论(0)
提交回复
热议问题