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

时间:2013-08-28 11:08:18

标签: shell unix awk

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

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

  

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

输出应为:

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

这可以grep还是awk完成?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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提供此建议。

答案 2 :(得分:3)

使用awk的解决方案:

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

答案 3 :(得分: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
%