如何将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
}'
答案 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)
您可以在awk中完成所有操作,而无需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
变量,以防下次循环时符号链接无法读取。