我有一个用逗号分隔的ID文件。我正在尝试用新行替换逗号。我试过了:
sed 's/,/\n/g' file
但它不起作用。我想念什么?
tr , '\n' < file-没有管道。
g在脚本的结束?没有它,我也会得到相同的行为。
我有一个用逗号分隔的ID文件。我正在尝试用新行替换逗号。我试过了:
sed 's/,/\n/g' file
但它不起作用。我想念什么?
tr , '\n' < file-没有管道。
g在脚本的结束?没有它,我也会得到相同的行为。
Answers:
使用tr来代替:
tr , '\n' < file
tr ',' ';' < input.csv > output.csv
使用ANSI-C引号引起来的字符串 $'string'
您需要使用反斜杠转义的文字换行符才能实现sed。至少在bash中,$''字符串将替换\n为真实的换行符,但是您必须将sed看到的反斜杠加倍以避开换行符,例如
echo "a,b" | sed -e $'s/,/\\\n/g'
echo "a,b" | sed -e $'s/,/\\n/g。
man bash。
sed -E $'s/<\\/br>/\\\n/g' file,无需安装gnu-sed
-e部分似乎没有必要。
sed 's/,/\
/g'
在Mac OS X上工作。
显然\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
\r与并不相同\n,这可能会破坏进一步的数据操作和使用。
\r!
这适用于MacOS Mountain Lion(10.8),Solaris 10(SunOS 5.10)和RHE Linux(Red Hat Enterprise Linux Server版本5.3,Tikanga)...
$ sed 's/{pattern}/\^J/g' foo.txt > foo2.txt
... ^J通过ctrl+ v+完成j。介意\之前^J。
PS,我知道RHEL中的sed是GNU,MacOS sed是基于FreeBSD的,尽管我不确定Solaris sed,但我相信这对任何sed都可以工作。YMMV通过...
要使其完整,这也可以:
echo "a,b" | sed "s/,/\\$(echo -e '\n\r')/"
tr解决方案,它已经是公认的答案。
\n\r而不是\r\n?我尝试\r\n了Windows上的必要命令。但是,执行完此操作后,会在其中留下许多^M回车符vim,因此我认为应该只是,\n但\n仅此一项是行不通的。
尽管我迟到了这篇文章,但只是更新我的发现。此答案仅适用于Mac OSX。
$ 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中)
只是要澄清一下:OSX(10.8; Darwin内核版本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-如上所述-或漂亮
sed "s/,/^M
/g"
注意:您必须输入< ctrl> -v,< return>才能在vi编辑器中获取'^ M'
$ echo $PATH | sed -e $'s/:/\\\n/g'
/usr/local/sbin
/Library/Oracle/instantclient_11_2/sdk
/usr/local/bin
...
在Mojave上为我工作
tr , '\n'。我想,sed\n视作纯文本。