【问题标题】:Loop over a single column condition statement in awk在 awk 中循环单列条件语句
【发布时间】:2017-04-11 13:32:26
【问题描述】:

如果语句为真,我想打印一行,但我想循环几个变体。这是一个批处理脚本:

Awk "($9==1) {print $0}" file > out.txt & type out.txt >> all_out.txt
Awk "($9==3) {print $0}" file > out.txt & type out.txt >> all_out.txt
Awk "($9==5) {print $0}" file > out.txt & type out.txt >> all_out.txt

但不是很优雅。可以将其写入 for 循环或 if 语句吗?我在安装了 cygwin 的 Windows 上使用 gnuawk。

任何帮助将不胜感激。

【问题讨论】:

    标签: loops if-statement awk gawk


    【解决方案1】:

    尝试:

    awk '($9==1) || ($9==3) || ($9==5)' Input_file  > all_out.txt
    

    awk '($9%2 != 0)' Input_file  > all_out.txt
    

    考虑到您想将所有条件输出到一个文件中,如果不是这样,请告诉我。

    【讨论】:

    • 这是一个更整洁的 1 班轮谢谢!但是,例如,如果我需要从 1、3、5 到 101 怎么办。你有什么想法?也许使用 i++?
    • 您是否需要检查任何模式,例如从 1 到 200 等的所有奇数值等等或其他什么?
    • 是的,我想要第九列的奇数值。而且我需要它灵活地达到高数字。因此,例如在脚本开头设置 x=200 之类的值。
    • ^1 用于第二个脚本。第一个应该只是awk '$9 ~ /^[135]$/' file
    • 感谢 Ed 的鼓励 :)
    【解决方案2】:

    试试这个 -

    $ awk '($9 ~ /^1$|^3$|^5$/) {print $0}' file 
    

    【讨论】:

    • 咳咳 - ($9 ~ /^1$|^3$|^5$/) {print $0} = $9 ~ /^[135]$/.
    • @EdMorton - 不错!在最短的答案中我无法与您竞争。谢谢你:)
    猜你喜欢
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 2015-02-10
    • 2019-03-25
    • 2013-12-28
    • 2014-08-19
    • 2020-11-21
    相关资源
    最近更新 更多