Linux awk 脚本中的 $0 和 $1(美元符号 0 或 1)是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15647263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:34:21  来源:igfitidea点击:

What are $0 and $1 (Dollar sign 0 or 1) in an awk script?

linuxawk

提问by 0x90

in awk:

awk

 1  tolower() ~ /mary/ { print "CI Record: " 
/regex/
; } 2
 how to compare the first field to “mary” in a case-insensitive fashion
!~ /Mary/ { print "Not Mary: " ##代码##; } 3 == "Mary" { print "Mary Record: " ##代码##; }

Why 1and 3compare $1and 2using $0?

为什么13比较$1,并2使用$0

采纳答案by anubhava

Actually example # 2is using a regex because of this syntax

实际上,# 2由于这种语法,示例正在使用正则表达式

##代码##

Which means in your example that if literal text Maryisn't found anywhere in whole line ($0) then execute awk code.

这意味着在您的示例中,如果Mary在整行 ( $0) 中的任何位置都找不到文字文本,则执行 awk 代码。

Whereas $1 == "Mary"is doing direct comparison between literal text Maryand field # 1 ($1).

$1 == "Mary"在文字文本Mary和字段 #1 ( $1)之间进行直接比较。

Finally tolower($1) ~ /mary/is again using ignre-case regex match on field # 1 and this means if $1has text mary(ignore-case) then execute rest of the awk code.

最后tolower($1) ~ /mary/再次在字段 #1 上使用 ignre-case regex 匹配,这意味着如果$1有文本mary(忽略大小写),则执行其余的 awk 代码。

回答by Advael

In awk, $0is the whole line of arguments, whereas $1is just the first argument in a list of arguments separated by spaces. So if I put "Mary had a little lamb" through awk, $1is "Mary", but $0is "Mary had a little lamb". The second line is trying to find the substring "Mary" in the whole line given to awk.

在 awk 中,$0是整行参数,而$1只是以空格分隔的参数列表中的第一个参数。因此,如果我通过 awk 输入“玛丽有一只小羊羔”,$1则是“玛丽”,而是$0“玛丽有一只小羊羔”。第二行试图在提供给 awk 的整行中找到子字符串“Mary”。

回答by keyboardP

From the description in your link (emphasis mine):

从您链接中的描述(强调我的):

The expression is generally either one of the fields or the result of an operation on one of the fields. For example, the following AWK filter rules show, respectively, how to compare the first fieldto “mary” in a case-insensitive fashion, how to match all recordsthat do not contain “Mary”, and how to do an exact comparison of the first fieldagainst “Mary”:

表达式通常是字段之一或对字段之一进行操作的结果。例如,下面的 AWK 过滤规则分别展示了如何以不区分大小写的方式将第一个字段与“mary”进行比较,如何匹配所有不包含“Mary”的记录,以及如何对在第一场对“玛丽”:

So breaking it down:

所以分解它:

First one:

第一:

##代码##

Because it's comparing the first field, it uses $1

因为它比较第一个字段,所以它使用 $1

how to match all records that do not contain “Mary”,

如何匹配所有不包含“玛丽”的记录,

Since it's comparing all records, it uses $0

由于它比较所有记录,因此它使用 $0

Third one

第三个

and how to do an exact comparison of the first field against “Mary”:

以及如何将第一个字段与“Mary”进行精确比较:

Comparing first field again, so it's using $1.

再次比较第一个字段,所以它使用$1.