2013-05-16 102 views
3

如何將awk變量傳遞給bash命令在awk內運行?如何將awk變量傳遞給bash命令

我使用awk來計算線程的運行總和爲每一個特定的過程,但我想用每個PID訪問/proc/$pid文件系統。

標記爲破線的線不正確,因爲$pid不存在。

如何導出awk變量pid到shell命令我得到awk來運行?

(增加了可讀性換行符)

$ ps -ALf | grep $PROC | grep -v grep | \   # get each pid 
    awk '{threads[$2]+=1} END \     # count num threads per pid 
     { \ 
      for (pid in threads) \ 
       "cat /proc/$pid/cwd"|getline cwd; \ # get 'cwd' (**broken**) 
       print cwd ": " threads[pid] \  # display 'cwd' and num threads 
     }' 
+0

爲什麼不在awk中做這麼多? – Johnsyweb

+2

不要做'grep ... | grep -v ... | awk ...',因爲awk可以完成grep(s)的工作。在linux上,你可以使用'ps -C $ PROC'來只顯示一個特定的進程(es)。 – TrueY

回答

2

你可以做一大堆的沒有任何grep s鏈路這樣的:

  • -v proc="${PROC}"環境變量${PROC}分配到awk變量:

    值得注意
    % ps -ALf | awk -v proc="${PROC}" ' 
    $0 ~ proc && !/awk/ { 
        threads[$2] += 1 
    } 
    END { 
        for (pid in threads) { 
         "readlink /proc/" pid "/cwd" | getline dir 
         printf "%d: %d %s\n", pid, threads[pid], dir 
         dir="" 
        } 
    }' 
    

    有幾件事情,proc

  • "readlink /proc/" pid "/cwd"連接三串。 awk中不需要任何級聯運算符。
  • dir=""復位dir變量,如果符號鏈接周圍的環中的下一個時間是不可讀。
2

awk不進行變量插值字符串內,你只要連接具有字符串(就像你在print語句來完成)的變量。

awk '{threads[$2]+=1} END     # count num threads per pid 
    { 
     for (pid in threads) 
      ("cat /proc/" pid "/cwd")|getline cwd; # get 'cwd' (**broken**) 
      print cwd ": " threads[pid]  # display 'cwd' and num threads 
    }' 

你也不需要所有的反斜槓。帶引號的字符串中的換行符不需要轉義(其中一些甚至不在換行符之前,後面有註釋)。

4

你不能貓/proc/$pid/cwd它是一個符號鏈接到一個目錄。解決符號鏈接的一種方法是使用來自coreutils的readlink

這裏是TrueY巴爾梅爾使用位的工作例如:

ps -C $PROC | 
awk '{ t[$1] } END { for(p in t) { "readlink -f /proc/" p "/cwd" | getline c; print c } }' 

幾件事情需要注意:

  • 管兼作續行字符。
  • 引用數組條目來創建它就足夠了(t[$1])。