$ 0 = $ 0在Awk中是什么意思? [英] What is the meaning of $0 = $0 in Awk?

查看:104
本文介绍了$ 0 = $ 0在Awk中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看一段代码时,我看到了以下命令:

While going through a piece of code I saw the below command:

grep "r" temp | awk '{FS=","; $0=$0} { print $1,$3}'

临时文件包含以下模式:

temp file contain the pattern like:

 1. r,1,5
 2. r,4,5
 3. ...

我无法理解awk命令中的 $ 0 = $ 0 语句是什么意思.

I could not understand what does the statement $0=$0 mean in awk command.

任何人都可以解释这是什么意思吗?

Can anyone explain what does it mean?

推荐答案

执行 $ 1 = $ 1 (或对字段的任何其他分配)时,它会导致记录重新编译,其中每个FS都会重建$ 0替换为OFS,但它不会更改NF(除非以前没有 $ 1 ,然后NF将从0变为1)或以任何其他方式重新评估记录.

When you do $1=$1 (or any other assignment to a field) it causes record recompilation where $0 is rebuilt with every FS replaced with OFS but it does not change NF (unless there was no $1 previously and then NF would change from 0 to 1) or reevaluate the record in any other way.

执行 $ 0 = $ 0 时,会导致字段拆分,其中会根据FS的当前值重新填充NF,$ 1,$ 2等,但不会将FS更改为OFS或修改$ 0以任何其他方式.

When you do $0=$0 it causes field splitting where NF, $1, $2, etc. are repopulated based on the current value of FS but it does not change the FSs to OFSs or modify $0 in any other way.

看:

$ echo 'a-b-c' |
    awk -F'-+' -v OFS='-' '
        function p() { printf "%d) %d: $0=%s, $2=%s\n", ++c,NF,$0,$2 }
        { p(); $2=""; p(); $1=$1; p(); $0=$0; p(); $1=$1; p() }
    '
1) 3: $0=a-b-c, $2=b
2) 3: $0=a--c, $2=
3) 3: $0=a--c, $2=
4) 2: $0=a--c, $2=c
5) 2: $0=a-c, $2=c

在上面请注意,即使将$ 2设置为null会导致连续2个-,并且-+ 的FS表示2个- s是单个分隔符,直到 $ 0 = $ 0 导致记录重新拆分为字段为止,它们才被处理,如输出步骤4所示.

Note in the above that even though setting $2 to null resulted in 2 consecutive -s and the FS of -+ means that 2 -s are a single separator, they are not treated as such until $0=$0 causes the record to be re-split into fields as shown in output step 4.

您拥有的代码:

awk '{FS=","; $0=$0}'

使用 $ 0 = $ 0 作为解决方法,以解决以下事实:在读取第一条记录并将其拆分为字段之后,才设置FS:

is using $0=$0 as a cludge to work around the fact that it's not setting FS until AFTER the first record has been read and split into fields:

$ printf 'a,b\nc,d\n' | awk '{print NF, $1}'
1 a,b
1 c,d

$ printf 'a,b\nc,d\n' | awk '{FS=","; print NF, $1}'
1 a,b
2 c

$ printf 'a,b\nc,d\n' | awk '{FS=","; $0=$0; print NF, $1}'
2 a
2 c

当然,正确的解决方案是在读取第一条记录之前简单地设置FS:

The correct solution, of course, is instead to simply set FS BEFORE The first record is read:

$ printf 'a,b\nc,d\n' | awk -F, '{print NF, $1}'
2 a
2 c

要清楚-将任何值分配给$ 0都会导致字段拆分,但不会导致记录重新编译,而将任何值分配给任何字段($ 1等)都会导致记录重新编译,但不会导致字段拆分:

To be clear - assigning any value to $0 causes field splitting, it does not cause record recompilation while assigning any value to any field ($1, etc.) causes record recompilation but not field splitting:

$ echo 'a-b-c' | awk -F'-+' -v OFS='#' '{$2=$2}1'
a#b#c
$ echo 'a-b-c' | awk -F'-+' -v OFS='#' '{$0=$0}1'
a-b-c

这篇关于$ 0 = $ 0在Awk中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆