多个gsub()调用如何在awk中一个接一个地工作?

时间:2018-10-05 15:27:18

标签: shell awk gsub

有人可以帮我解释以下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

1 个答案:

答案 0 :(得分: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()的交互方式是添加额外的打印语句:

#!/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

...因此您可以清楚地看到每个操作都已发生(第一个操作删除了空格,第二个操作删除了{)。

相关问题