我需要编写一个shell脚本来通过插入换行符来重新格式化文件。条件是当我们在文件中遇到逗号时应该插入换行符。只要遇到逗号就在文件中插入换行符 - Shell脚本
例如,如果文件包含:
这是一个文件,即应被加入,用,行突破,当我们发现,一个逗号。
输出应该是:
this
is a file
that should
be added
with a
line break
when we find a
a comma.
可以这样做grep
或awk
?
我需要编写一个shell脚本来通过插入换行符来重新格式化文件。条件是当我们在文件中遇到逗号时应该插入换行符。只要遇到逗号就在文件中插入换行符 - Shell脚本
例如,如果文件包含:
这是一个文件,即应被加入,用,行突破,当我们发现,一个逗号。
输出应该是:
this
is a file
that should
be added
with a
line break
when we find a
a comma.
可以这样做grep
或awk
?
使用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了这个建议。
这是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
解决方案用awk:
awk 1 RS=", " file
this
is a file
that should
be added
with a
line break
when we find
a comma.
+1但恕我直言,你应该总是说当一个发布的解决方案是特定于一个版本的awk,而这个是GNU-awk特定的礼貌RS的多字符设置。我认为你应该把它设为RS =“,[[:space:]] *”,这样它会在逗号后去掉任何空格,并处理逗号之后没有空格的情况。 –
感谢您提供此信息。知道支持什么版本并不容易,但我会将这些信息添加到我的脑海中。为什么不使用'RS =“,*”'而不是'RS =“,[[:space:]] *”' – Jotne
他可能在逗号后面有一个制表符或其他空格,而不是空白charcater,恕我直言,你也可以照顾任何/所有的人。 –
我很好奇,为什么你会认为grep可能是这个工作的合适工具。 'grep'这个名字来自'g/re/p',它们是'ed'命令来搜索一个RE并打印匹配的行。这就是所有grep的目的 - 搜索一个RE并打印结果,它不是一个编辑器。 –