4

我正在尝试通过 Bash shell 中的多个命令一次通过管道输出 awk 命令的输出,根据我的知识,我想出了这个:

awk '$13 ~ /type/ {print $15}' filename.txt | (wc -l || sort -u)

我希望对 awk 命令的结果进行计数和排序,我该如何做到这一点?即使使用 && 命令它也不起作用,它会执行第一个命令然后退出。我想这是我对 bash 的了解失败了。

提前致谢。

4

5 回答 5

5

如果要在一行中将输出发送到两个不同的命令,则需要进行进程替换。

试试这个:

awk '$13 ~ /type/ {print $15}' filename.txt | tee >(wc -l >&2) | sort -u

这将输出 stderr 上的行数和 stdout 上的排序输出。如果您需要 stdout 上的行数,则可以省略>&2,但随后它将传递给 sort 调用并(很可能)排序到输出的顶部。

编辑:根据进一步测试更正了对所发生情况的描述。

于 2010-08-03T15:35:37.810 回答
4

在那种情况下,您是否计算 awk ,为什么需要管道?不要让它更复杂

awk '$13 ~ /type/ {print $15;c++}END{print c} ' filename.txt | sort -u
于 2010-08-03T15:50:56.253 回答
1

如果输出中的大小不是太大而无法放入内存,并且出于性能原因不需要wcsort命令并行工作,这里有一个相对简单的解决方案:

output=$(awk '$13 ~ /type/ {print $15}' filename.txt; echo a)
printf "%s" "${output%a}" | sort -u
printf "%s" "${output%a}" | wc -l

额外的复杂性a是,如果awk命令可能在输入的末尾打印一些空行,$()构造会删除这些空行。您可以轻松选择哪个sortwc应该首先出现。


这是一种适用于任何 POSIX shell(ash、bash、ksh、zsh、...)的方法,但仅适用于具有/dev/fd(包括最近的 Linux、*BSD 和 Solaris)的系统。就像Walter 使用 bash、ksh93 和 zsh 中可用的更简单方法的类似构造一样, 的输出wc和 的输出sort可以混合使用。

{
  awk '$13 ~ /type/ {print $15}' filename.txt |
  tee /dev/fd3 |
  wc -l
} 3>&1 1>&3 | sort -u

If you both need to deal with intermediate output that doesn't comfortably fit in memory and don't want to have the output of the two commands intermixed, I don't think there's an easy way in a POSIX shell, though it should be doable with ksh or zsh coprocesses.

于 2010-08-03T22:39:17.430 回答
0

我认为更大的问题是:您期望输出是什么?

如果你想做两件事,那么做两件事:

awk '$13 ~ /type/ {print $15}' filename.txt > tempfile
wc -l < tempfile
sort -u < tempfile
rm tempfile
于 2010-08-03T15:32:10.370 回答
0

您希望将使用 mkfifo 创建的命名管道与 tee 结合使用。一个例子是http://www.softpanorama.org/Tools/tee.shtml

于 2010-08-03T15:33:24.357 回答