终端中的猫似乎表现得异常随机

Cat in terminal seems to behave erratically random

我有一个文件,内容如下:

2)    Wiegley   Maths      90
3)    Artur     Biology    87
4)    Drew      English    85
5)    Phils     History    89

我将它存储在一个名为 marks.txt 的文件中。

在shell中,我运行使用sedawk进行一些操作(使用xfce4终端仿真器)

awk '{print  "\t" }' marks.txt | sed -e '/^E/d' > foo.txt | cat foo.txt

当我快速执行相同的命令(向上箭头并输入)时,它有时会给我文件 foo.txt 的输出。但有时当快速重复相同的命令时,它没有给我任何输出。

我无法理解这一点,从我的 shell 看来,这似乎是一种 运行dom 行为。当我快速重复相同的命令时,谁能解释为什么 cat 有时会给出输出?它不会先等待 awksed 的输出吗?

通向 cat 的管道没有意义,因为您没有通过它传递任何数据,也没有尝试使用它(为此,您可以使用 cat -)。

您的命令会打开三个子外壳。中间的 > 将在等待任何输入之前截断文件 foo.txtcat foo.txt 将尝试在 或多或少 同时访问文件 foo.txt。根据这两件事中哪一件先发生,foo.txt 将包含上次您 运行 命令时的内容,否则它将为空。

郑重声明,您的命令最好写成:

awk -v OFS='\t' ' !~ /^E/ { print ,  }' marks.txt > foo.txt

如果您想将结果打印到标准输出并同时写入文件,一种选择是使用 tee.

awk -v OFS='\t' ' !~ /^E/ { print ,  }' marks.txt | tee foo.txt

这将打印第三个字段不以 E 开头的任何行的第三个和第四个字段。

您的问题似乎与管道和重定向之间的优先级有关。

Splitting a command line into piped commands is done before doing file redirection. File redirection happens second, and if present, has precedence over pipe redirection. (The file redirection always wins.)

发件人:http://www.cs.colostate.edu/~mcrob/toolbox/unix/redirection

您可以在此处找到一些示例:

Pipe | Redirection < > Precedence