如何将awk变量传递给bash命令

时间:2013-05-16 06:49:12

标签: linux bash awk

如何将awk变量传递给在bash内运行的awk命令?

我正在使用awk计算每个特定进程的线程运行总和,但后来我想使用每个pid来访问/proc/$pid文件系统。

下面标有已损坏的行不正确,因为$pid不存在。

如何将awk变量pid导出到我运行的awk的shell命令中?

(为了便于阅读而添加了换行符)

$ 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
         }'

3 个答案:

答案 0 :(得分:4)

你不能cat /proc/$pid/cwd它是目录的符号链接。解决符号链接的一种方法是使用coreutils中的readlink

以下是使用 TrueY Barmer 中的位的工作示例:

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

有几点需要注意:

  • 管道兼作续行字符。
  • 足以引用数组条目来创建它(t[$1])。

答案 1 :(得分: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
     }'

您也不需要所有这些反斜杠。引用字符串中的换行符不需要进行转义(其中一些换行符甚至不在换行符之前,后面还有注释)。

答案 2 :(得分:2)

您可以在中完成所有操作,而无需grep个链接:

% 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=""
    }
}'

值得注意的一些事情:

  • -v proc="${PROC}"将环境变量${PROC}分配给awk变量proc
  • "readlink /proc/" pid "/cwd"连接三个字符串。 awk中不需要任何连接运算符。
  • dir=""重置dir变量,以防下次循环时符号链接无法读取。