我有一个用逗号分隔的字符串文件。我正试着用新的一行替换逗号。我试过了:
sed 's/,/\n/g' file
但这并不奏效。我错过了什么?
我有一个用逗号分隔的字符串文件。我正试着用新的一行替换逗号。我试过了:
sed 's/,/\n/g' file
但这并不奏效。我错过了什么?
当前回答
使用ANSI-C引用字符串$'string'
您需要一个反斜杠转义的文字换行符来访问sed。 至少在bash中,$ "字符串将用真正的换行符替换\n,但随后您必须将sed看到的反斜杠加倍以转义换行符,例如:
echo "a,b" | sed -e $'s/,/\\\n/g'
注意,这并不适用于所有shell,但适用于最常见的shell。
其他回答
虽然我写这篇文章晚了,只是更新我的发现。这个答案只适用于Mac OS X。
$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern
在上面的命令中,我尝试用Shift+Enter添加新行,但没有工作。所以这一次我尝试了“转义”的“未转义换行”,因为错误告诉。
$ sed 's/new/\
> /g' m1.json > m2.json
成功了!(适用于Mac OS X 10.9.3)
使用ANSI-C引用字符串$'string'
您需要一个反斜杠转义的文字换行符来访问sed。 至少在bash中,$ "字符串将用真正的换行符替换\n,但随后您必须将sed看到的反斜杠加倍以转义换行符,例如:
echo "a,b" | sed -e $'s/,/\\\n/g'
注意,这并不适用于所有shell,但适用于最常见的shell。
macOS Mojave上的sed于2005年发布,因此一种解决方案是安装gnu-sed,
brew install gnu-sed
然后使用gsed就可以了,
gsed 's/,/\n/g' file
如果你更喜欢sed,只需sudo sh -c 'echo /usr/local/opt/gnu-sed/libexec/gnubin > /etc/paths.D /brew',由brew info gnu-sed推荐。重新启动term,然后命令行中的sed为gsed。
显然\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
只是为了澄清: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'