如何有选择地 awk 字符串?
如果文件中具有不确定宽度的文本行包含文本“Line-to-reorder”,并且我只想翻转并显示前三个标记的顺序,我可以这样做:
# cat file.txt | awk '/Line-to-reorder/ { print $3 $2 $1 }'
How can I let line of text that don't匹配标准是否未改变?
其次,如何在匹配的行上显示剩余的标记(该行的剩余部分)?
(awk 是首选工具,因为我的嵌入式系统的 busybox 实现就有它。)
If text lines of indeterminate width had in a file had text "Line-to-reorder", and I only wanted to flip and display the order of the first three tokens I can do:
# cat file.txt | awk '/Line-to-reorder/ { print $3 $2 $1 }'
How can I let lines of text that don't have the matching criteria pass through unaltered?
Secondly, How can I display the remainder of the tokens (the remainder of the line) on the matched line?
(awk is the tool of choice since my embedded system's busybox implementation has it.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个简单的脚本回答了您的两个问题:
cat
This simple script answers both your questions:
cat
没有必要执行任何
if...else
,只需执行匹配/不匹配即可。如果该行匹配,则将打印字段 3、2 和 1,然后按原始顺序打印其余字段。如果没有,它将按原样打印整行。
分解为
awk
脚本:使用以下命令运行此脚本:
此
awk
脚本将文件名作为参数(因为awk
这样做),所以cat
对于这两种调用方法都不是必需的。It's not necessary to do any
if...else
, just do a match/not-match.This prints fields 3, 2, and 1 followed by the rest of the fields in their original order if the line matches. If it doesn't, it prints the whole line as-is.
Broken out into an
awk
script:Run this with something like:
This
awk
script takes a filename as an argument (becauseawk
does) and socat
isn't necessary for either invocation method.最好的选择可能是匹配所有行(无模式),然后在操作中执行
if ... else
。类似的东西
best option is probably to match all lines (no pattern) and then do
if ... else
in the action.something like
此参考可能会有所帮助
This reference may help