在 unix shell 脚本中将换行符替换为空格
我有一个包含一些记录的文本文件。每条记录分为 4 行(并不总是 4 行),如示例所示:
----
row1
row2
row3
row4
----
row1
etc...
每行以换行符 (LF) 结尾。 好的,我只需要获取一行记录,用空格替换 LF 字符,例如:
---- row1 row2 row3 row4
---- row1 row2 ...etcetera
对解决方案有任何帮助或建议吗? 提前致谢。
I have a text file containing some records. Each record is splitted in 4 rows (not always 4), like the example:
----
row1
row2
row3
row4
----
row1
etc...
Each row is ended with the Line Feed character (LF).
Ok, I need to obtain the record in only one line, replacing the LF character with a Space, like in example:
---- row1 row2 row3 row4
---- row1 row2 ...etcetera
Any help or suggestion for the solution?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
也许这可以工作?
maybe this can work ?
或全部在一个 awk 中
or all in one awk
一个更简单的方法是这样的
And a much simpler approach would be this
您需要知道记录之间的分隔符到底是什么。在您的示例中,它看起来像是“----”,但您也说过记录数量是可变的。
无论如何,最好使用这样的代码来完成类似的事情:
You need to know what exactly is the separator between the records. In your example it looks like it's '----', but you also said that there is a variable number of records.
Anyway, things like that are best done using code like this:
awk 'BEGIN {RS="----"; FS=“\n”; OFS=" "} FNR==1 {下一个} {$1=RS $1;打印}'输入.文件
awk 'BEGIN {RS="----"; FS="\n"; OFS=" "} FNR==1 {next} {$1=RS $1; print}' input.file
为此,请使用 awk 而不是 shell 脚本
迭代文本文件并根据行内容执行不同的操作,这正是 awk 的设计目的。
在 21 世纪,shell 脚本应该保持简单,而其他工具则用于复杂的逻辑。
Use awk for this rather than a shell script
Iterating through a text file and doing different things based on the line contents, is precisely what awk was designed to do.
In the 21st century shell scripts should be kept simple and other tools used for complex logic.