如何防止 awk 将换行符附加到匹配项
我正在编写一个 bash 脚本来解析制表符分隔的文本文件中的一些字段,并将它们附加到文件本身的文件名中。我可以使用 awk 很好地解析这些字段,但它们附加了换行符。我想从结果中删除这些换行符,或者理想情况下首先阻止 awk 附加它们。目前仅从存储的字符串中回显的示例代码:
#!/bin/bash
echo "Usage: sh extract.sh filename.txt (or *.txt)"
for filenam in "$@"
do
timestring=$(awk 'BEGIN{ FS="\t"; RS="\n"; ORS="_"; OFS="_"}
/Conditions/ {printf $2}
/Date/ {printf $2}
/Time/ {printf $2}
END {}' $filenam)
echo $timestring
done
目前,每次找到匹配项时,它都会覆盖以前的任何匹配项,因为 \n 附加到字符串末尾。我该如何防止这种情况发生? (这样我就有条件日期时间作为字符串,没有任何换行符)。
抱歉,如果这看起来是一个简单的问题,但我已经在谷歌上搜索了几个小时并尝试了各种方法,但我被难住了。谢谢!
I'm writing a bash script to parse some fields from a tab delimited text file and append them to the filename of the file itself. I can parse the fields out just fine using awk, but they come with a newline appended. I would like to either strip out those newlines from the result or ideally prevent awk from appending them in the first place. Sample code with just an echo out of the stored string for now:
#!/bin/bash
echo "Usage: sh extract.sh filename.txt (or *.txt)"
for filenam in "$@"
do
timestring=$(awk 'BEGIN{ FS="\t"; RS="\n"; ORS="_"; OFS="_"}
/Conditions/ {printf $2}
/Date/ {printf $2}
/Time/ {printf $2}
END {}' $filenam)
echo $timestring
done
At the moment, every time it finds a match, it overwrites any previous matches, because of the \n appended to the end of the string. How do I prevent that? (so that I have conditions_date_time as a string, without any newlines).
Sorry if this seems like a simple question, but I've been googling for hours and tried all manner of things and I'm stumped. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的脚本中,使用
print
而不是printf
,例如print $2
。至于覆盖,如果您正在处理的文本文件具有
\r\n
行结尾而不是\n
,则可能会发生这种情况。如果是这种情况,请将输入记录分隔符设置为\r\n
,例如RS="\r\n"
。In your script, use
print
instead ofprintf
, e.g.print $2
.As for the overwriting, this could happen if the text file that you're processing has
\r\n
line endings, instead of\n
. If this is the case, set the input record separator to\r\n
, e.g.RS="\r\n"
.在将文件传递给
awk
之前,对文件执行dos2unix
before you pass the file to
awk
, do ados2unix
on your file尝试类似的东西
它未经测试,但你应该明白。
Try something like
It's untested, but you should get the idea.