我有一个用逗号分隔的字符串文件。我正试着用新的一行替换逗号。我试过了:

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

但这并不奏效。我错过了什么?


当前回答

$ echo $PATH | sed -e $'s/:/\\\n/g' 
/usr/local/sbin
/Library/Oracle/instantclient_11_2/sdk
/usr/local/bin

...

在莫哈韦对我有用

其他回答

只是为了澄清:OSX上sed的手册页(10.8;达尔文内核版本12.4.0)说:

[…]

Sed正则表达式

 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.

[…]

所以我想一个人必须使用tr -如上所述-或者nitty

sed "s/,/^M
/g"

注意:你必须输入<ctrl>-v,<return>才能在vi编辑器中得到'^M'

我发现了另一个同样有效的命令。

find your_filename.txt -type f -exec sed -i 's/,/\n/g' {} \;

显然\r是钥匙!

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

转换:

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

:

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

这适用于MacOS Mountain Lion (10.8), Solaris 10 (SunOS 5.10)和RHE Linux (Red Hat Enterprise Linux Server release 5.3, Tikanga)……

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

... 这里的^J是通过ctrl+v+ J完成的。注意^J前面的\。

另外,我知道RHEL的sed是GNU的,MacOS的sed是基于FreeBSD的,虽然我不确定Solaris的sed,但我相信这对任何sed都适用。YMMV tho”……

为了使它完整,也可以这样做:

echo "a,b" | sed "s/,/\\$(echo -e '\n\r')/"