每当遇到逗号时在文件中插入换行符 - Shell脚本

问题描述 投票:3回答:4

我需要编写一个shell脚本来通过插入换行符来重新格式化文件。条件是当我们在文件中遇到逗号时应插入换行符。

例如,如果文件delimiter.txt包含:

这是一个文件,当我们找到逗号时,应该添加一个换行符。

输出应该是:

this
is a file
that should
be added
with a
line break
when we find a
a comma.

这可以做grepawk

shell unix awk
4个回答
5
投票

使用GNU sed

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

输出:

this
is a file
that should
be added
with a
line break
when we find a
a comma. 

注意:上面的语法仅适用于将\n作为行分隔符作为Linux和最多UNIX的系统。

如果您需要脚本中的门户网站解决方案,请使用以下表达式,该表达式使用文字新行而不是\n

sed 's/,[[:space:]]/\
/g' your.file

感谢@EdMorten提供此建议。


6
投票

这就是tr的用途

$ tr ',' '\n' <<< 'this, is a file, that should, be added, with a, line break, when we find, a comma.'
this
 is a file
 that should
 be added
 with a
 line break
 when we find
 a comma.

或者如果你必须使用awk:

awk '{gsub(", ", "\n", $0)}1' delimiter.txt

3
投票

使用awk的解决方案:

awk 1 RS=", " file
this
is a file
that should
be added
with a
line break
when we find
a comma.

0
投票

这是使用perl的解决方案:

perl -pe 's#,#\n#g'

这是一个在OpenBSD或OS X上正常工作的示例:

% echo 'a,b,c,d,e' | perl -pe 's#,#\n#g'
a
b
c
d
e
%

例如,与之前的sed解决方案不同,这个perl可以在任何地方使用,因为相同的搜索/替换片段不适用于OpenBSD或OS X上的BSD sed

% echo 'a,b,c,d,e' | sed -E 's#,#\n#g'
anbncndne
%
© www.soinside.com 2019 - 2024. All rights reserved.