【问题标题】:How do multiple gsub() calls work together one after another in awk?多个 gsub() 调用如何在 awk 中一个接一个地一起工作?
【发布时间】:2018-10-05 15:27:18
【问题描述】:

谁能帮我解释下面的 awk 命令?我对这里的多个 gsub 函数在做什么感到困惑。

cat vslist.txt | awk '\''/:/{gsub(/ /, \"\", $0);gsub(/{/, \",\", $0);printf $s,$1}'\''");printf "\n"}' 

vslist.txt

ltm pool PL_Axxxxx_POOL {
    members {
        ND_APIxxxxxx:7807 {
            address 12.7.21.6
            app-service none
            connection-limit 0
            description none
            dynamic-ratio 1

        ND_APIxxxxxx:7809 {
            address 12.7.21.5
            app-service none
            connection-limit 0
            description none
            dynamic-ratio 1

        ND_APIxxxxxx:7808 {
            address 12.7.21.9
            app-service none
            connection-limit 0
            description none
            dynamic-ratio 1

输出

    ND_APIxxxxxx:7807
    ND_APIxxxxxx:7809
    ND_APIxxxxxx:7808

【问题讨论】:

  • “请解释这段代码”问题通常不在我们的范围内;请参阅Meta Stack Overflow 上的meta.stackoverflow.com/questions/253894/…。也就是说,缩小问题范围可能会改善问题:您了解单个 gsub 调用的作用吗?您了解gsubs 之一,但不了解另一个?还是关于它们如何结合的真正误解?
  • 顺便说一句,奇怪的引用是怎么回事?这里的反斜杠比在常规 shell 上下文中运行它所需的要多得多。这是从其他某种引用上下文中的代码中获取的吗?
  • ...哦,等等,$s 是来自外部的变量吗?好的,以正确的方式(使用awk -v)传递该变量将使您的其余代码更易于阅读。 (此外,我们需要知道它包含什么才能正确理解此脚本;代码段应经过测试以使其足够完整,以便有人重现问题中的行为,如minimal reproducible example 页面中的 id 所述帮助中心)。

标签: shell awk gsub


【解决方案1】:

gsub() 调用修改它们正在操作的变量(在本例中为$0就地。因此,一个接一个地,第二个进一步改变了第一个的输出。

考虑以下脚本的简化和注释版本:

#!/bin/bash
awk '
  /:/ {                 # run the below code only for lines that contain :
    gsub(/ /, "", $0);  # remove all spaces
    gsub(/{/, "", $0);  # remove opening curly braces
    print $1            # print the first column in what's next
  }
' <vslist.awk           # with stdin from vslist.awk

使用打印语句进行调试(或者,如何自己查看)

顺便说一句,您可以亲自了解gsub()s 如何交互的一种方法是添加额外的打印语句:

#!/bin/bash
awk '
  /:/ {
    print "Input:                                " $0;
    gsub(/ /, "", $0);
    print "After first gsub:                     " $0;
    gsub(/{/, "", $0);
    print "After second gsub, the whole line is: " $0;
    print $1;
  }
' <vslist.awk           # with stdin from vslist.awk

使用该仪器,您的示例输入的输出为:

Input:                                        ND_APIxxxxxx:7807 {
After first gsub:                     ND_APIxxxxxx:7807{
After second gsub, the whole line is: ND_APIxxxxxx:7807
ND_APIxxxxxx:7807
Input:                                        ND_APIxxxxxx:7809 {
After first gsub:                     ND_APIxxxxxx:7809{
After second gsub, the whole line is: ND_APIxxxxxx:7809
ND_APIxxxxxx:7809
Input:                                        ND_APIxxxxxx:7808 {
After first gsub:                     ND_APIxxxxxx:7808{
After second gsub, the whole line is: ND_APIxxxxxx:7808
ND_APIxxxxxx:7808

...所以您可以清楚地看到每个操作的发生(第一个删除空格,第二个删除{)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多