Awk

AWK - 處理 wmctrl 輸出的最後一列中的空格

  • December 28, 2021

作為學習awk的第一個項目,我想重新格式化wmctrl命令的輸出,它可以在 Debian 11 中像這樣安裝:

sudo apt install wmctrl

要列出有關我打開的所有視窗的資訊,我執行以下命令:

wmctrl -lpG

樣本輸出:

0x0120002b  4 7      2    157  3836 2068 my-pc window - AWK - Dealing with spaces in the last column of output from wmctrl - Unix & Linux Stack Exchange — Firefox

在上面的命令中,我永遠記不起每一列的含義,所以我想使用 AWK 將它分成名稱/值對:

wmctrl -lpG | awk '{print "----------------------\nWindow ID: " $1 "\nDesktop Number: " $2 "\nProcess ID: " $3 "\nx-offset: " $4 "\ny-offset: " $5 "\nwidth: " $6 "\nheight: " $7 "\nMachine Name: " $8 "\nWindow Title: " $9}'

樣本輸出:

----------------------
Window ID: 0x0120002b
Desktop Number: 4
Process ID: 7
x-offset: 2
y-offset: 134
width: 3836
height: 2068
Machine Name: my-pc
Window Title: window

期望的輸出:

----------------------
Window ID: 0x0120002b
Desktop Number: 4
Process ID: 7
x-offset: 2
y-offset: 134
width: 3836
height: 2068
Machine Name: my-pc
Window Title: window - AWK - Dealing with spaces in the last column of output from wmctrl - Unix & Linux Stack Exchange — Firefox

但是,我無法弄清楚如何處理由(因為第9wmctrl -lpG列包含空格)輸出的第 9 列。請注意,我只得到視窗標題的第一個單詞而不是整個視窗標題

有沒有簡單的方法來解決這個問題?

wmctrl -lpG \
| awk '{
        tmp=$0;
        # remove first 8 fields from tmp
        sub(/^[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ /,"",tmp);
        print "----------------------\nWindow ID: " $1 "\nDesktop Number: " $2 "\nProcess ID: " $3 "\nx-offset: " $4 "\ny-offset: " $5 "\nwidth: " $6 "\nheight: " $7 "\nMachine Name: " $8 "\nWindow Title: " tmp
      }'

輸出:

----------------------
Window ID: 0x0120002b
Desktop Number: 4
Process ID: 7
x-offset: 2
y-offset: 157
width: 3836
height: 2068
Machine Name: sidekick
Window Title: window - AWK - Dealing with spaces in the last column of output from wmctrl - Unix & Linux Stack Exchange — Firefox

引用自:https://unix.stackexchange.com/questions/684109