详细解释AWK语法(NR,FNR,NF)

发布于 2025-01-09 09:24:21 字数 304 浏览 0 评论 0原文

我正在学习使用 awk 进行文件比较。

我发现语法如下,

awk '
(NR == FNR) { 
    s[$0]
    next 
} 
{ 
    for (i=1; i<=NF; i++) 
        if ($i in s) 
            delete s[$i] 
} 
END { 
    for (i in s) 
        print i 
}' tests tests2

我无法理解语法是什么......你能详细解释一下吗?

它到底有什么作用?

I am learning file comparison using awk.

I found syntax like below,

awk '
(NR == FNR) { 
    s[$0]
    next 
} 
{ 
    for (i=1; i<=NF; i++) 
        if ($i in s) 
            delete s[$i] 
} 
END { 
    for (i in s) 
        print i 
}' tests tests2

I couldn't understand what is the Syntax ...Can you please explain in detail?

What exactly does it do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜巴黎 2025-01-16 09:24:21
awk '                      # use awk
(NR == FNR) {              # process first file
    s[$0]                  # hash the whole record to array s
    next                   # process the next record of the first file
} 
{                          # process the second file
    for (i=1; i<=NF; i++)  # for each field in record
        if ($i in s)       # if field value found in the hash
            delete s[$i]   # delete the value from the hash
} 
END {                      # after processing both files 
    for (i in s)           # all leftover values in s
        print i            # are output
}' tests tests2

例如,对于文件:

tests:
1
2
3

tests2:
1 2
4 5

程序将输出:

3
awk '                      # use awk
(NR == FNR) {              # process first file
    s[$0]                  # hash the whole record to array s
    next                   # process the next record of the first file
} 
{                          # process the second file
    for (i=1; i<=NF; i++)  # for each field in record
        if ($i in s)       # if field value found in the hash
            delete s[$i]   # delete the value from the hash
} 
END {                      # after processing both files 
    for (i in s)           # all leftover values in s
        print i            # are output
}' tests tests2

For example, for files:

tests:
1
2
3

tests2:
1 2
4 5

program would output:

3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文