【问题标题】:AWK - how to improve this example with gsub?AWK - 如何用 gsub 改进这个例子?
【发布时间】:2012-06-02 05:58:34
【问题描述】:

我有一个文件:

one one one
one one
one one
one
one
one

这个命令替换了5次“一”、“三”

$ awk '{for(i=1; NF>=i; i++)if($i~/one/)a++}{if(a<=5) gsub("one", "three"); print }' file

three three three
three three
one one
one
one
one

现在同样的事情,但是 6 次:

$ awk '{for(i=1; NF>=i; i++)if($i~/one/)a++}{if(a<=6) gsub("one", "three"); print }' file

three three three
three three
one one
one
one
one

如何改进上面的例子?我想要这个结果:

three three three
three three
three one
one
one
one

感谢您的帮助。

【问题讨论】:

    标签: awk gsub


    【解决方案1】:
    awk '{for (i=1; i<=NF; i++) {if ($i ~ /one/) {a++; if(a <= 6) sub("one", "three", $i)}}; print}'
    

    【讨论】:

    • 我有一个问题。是否有必要使用上面的例子,写sub("one", "three", $i)而不是:sub("one", "three")?谢谢。
    • @Tedee12345:如果您不指定字段(或变量等其他内容),则默认使用$0sub() 仅替换第一个实例,因此您永远不会在第二行使用默认值 $0 得到“三三”。 gsub() 默认为 $0 不允许您在第三行使用“三一”,因为它是全局的,因为它会给您“三三”。您仍然可以像这样使用gsubgsub("one", "three", 1) 如果您希望“oneoneone one”变为“threethreethree one”,因为“global”只会应用于字段 1。
    • 否则,对于简单的替换(正如您在问题中所做的那样显示,您根本不需要subgsub。您可以直接分配if(a &lt;= 6) {$i = "three"}
    • @Dennis_Williamson 感谢您的澄清。
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多