Piping into grep using cat returns error: no such file or directory

Piping into grep using cat returns error: no such file or directory

我正在 bash 练习。当我尝试此命令时,出现错误:"grep: where: No such file or directory".

cat file2.txt | tr " " "\n" | grep –i where | wc -l
Content of file2.txt = 1 2 3 4 where 5 where 7 where

你的命令没有问题。它应该按原样工作。也许你复制粘贴了一些不可见的字符,这些字符弄乱了它。复制粘贴以下命令并通过更改您的实际值重试。

cat script.sh | tr ' ' '\n' | grep -i echo | wc -l

如果有效请告诉我。

为什么报错信息

如果您从问题中复制命令并使用 UTF-8 到 Unicode 解释器对其进行分析,则 i 之前的 是破折号 U+2013 而不是连字符减号- (U+002D)。这意味着 grep–i 视为要搜索的模式,将 where 视为要搜索的文件,该文件不存在 — 如错误消息所述。

$ echo "grep –i where | wc -l" | utf8-unicode -w 3
0x67           = U+0067
0x72           = U+0072
0x65           = U+0065
0x70           = U+0070
0x20           = U+0020
0xE2 0x80 0x93 = U+2013
0x69           = U+0069
0x20           = U+0020
0x77           = U+0077
0x68           = U+0068
0x65           = U+0065
0x72           = U+0072
0x65           = U+0065
0x20           = U+0020
0x7C           = U+007C
0x20           = U+0020
0x77           = U+0077
0x63           = U+0063
0x20           = U+0020
0x2D           = U+002D
0x6C           = U+006C
$

utf8-unicode 的代码现在可以在我的 SOQ (Stack Overflow Questions) repository on GitHub as file utf8-unicode-1.11.tgz in the packages 子目录中找到。这是当前版本 — utf8-unicode -V 报告 utf8-unicode: UTF8-UNICODE Version 1.11 (2017-06-12 06:22:15)utf8-unicode -h 提供帮助。使用 -w 3 意味着它为每个代码点留下了足够的 space 3 字节宽,从而导致更多的列输出(默认为 -w 1)。

其他改进

在上面的分析中,我没有提到如何更普遍地改进脚本。如果你有一个足够现代的 GNU grep,你可以只使用两个命令:

$ grep -iow where file2.txt | wc -l

你不能将它缩减为一个命令;使用 grep -ciow where file2.txt 得到 1,而不是 3(因为只有一个输入行匹配)。

对于非 GNU grep,您可能需要使用:

$ tr ' ' '\n' < file2.txt | grep -ic where

Beware UUoC — Useless Use of cat.

多种方式:

使用 GNU grep:

grep -oiw echo script.sh | wc -l
  • -o: 只输出匹配。
  • -i: 匹配不区分大小写。
  • -w: 全词匹配。
  • wc -l: 计数匹配。

使用 sed 将命令拆分为每行一个:

sed 's/[[:space:][:punct:]]\+/\n/g' script.sh | grep -ciF echo
  • sed 's/[[:space:][:punct:]]\+/\n/g': 用换行符替换所有空格、回车returns、制表符、标点符号。
  • grep -ciF echo:计算不区分大小写的纯文本匹配行数 echo(无正则表达式)。