使用 ls –a
和 grep
,您将如何使用单个 grep 命令列出 /usr 中以字母 p 或字母 r 或字母 s 开头的所有文件的名称?
这是对的吗?
ls –a | grep [prs] /usr
原文由 Nicole Romain 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 ls –a
和 grep
,您将如何使用单个 grep 命令列出 /usr 中以字母 p 或字母 r 或字母 s 开头的所有文件的名称?
这是对的吗?
ls –a | grep [prs] /usr
原文由 Nicole Romain 发布,翻译遵循 CC BY-SA 4.0 许可协议
7 回答5.3k 阅读
4 回答4k 阅读
2 回答5.9k 阅读✓ 已解决
2 回答2.5k 阅读✓ 已解决
1 回答2.3k 阅读✓ 已解决
2 回答795 阅读✓ 已解决
2 回答3.2k 阅读
将从
r
ls -a /usr
p
输出中选择以/usr
84250f95d1f2b2f8ffd45726c2c58 中的任何一个开头的行---
或s
字符。这可能是您的老师所期望的,但这是错误的,或者至少不可靠。
文件名可以由多行组成,因为换行符与 Linux 或任何 unix 上的文件名中的任何字符一样有效。 So that command doesn’t return the files whose name starts with
p
,q
ors
, but the lines of the filenames that start withp
,q
或s
。通常,您不能可靠地对ls
的输出进行后处理。-a
是包含隐藏文件,即名称以.
开头的文件。由于您只想要以p
、q
或s
的那些,那是多余的。注意:
会更加错误。 First
^
is a special character in a few shells like the Bourne shell,rc
,es
orzsh -o extendedglob
(though OK inbash
或其他 POSIX shell)。然后,在大多数 shell 中(
fish
是一个明显的例外),[pqs]
是一个通配符。这意味着^[qps]
旨在由 shell 扩展为与该模式匹配的文件列表(相对于当前目录)。因此,在那些像
bash
这样的 shell 中,它们不会特别处理^
,如果当前目录中有一个名为^p
的文件,那将变为If there’s no matching file, in
csh
,tcsh
,zsh
orbash -O failglob
, you’ll get an error message and the command will被取消。 Inzsh -o extendedglob
where^
is a globbing operator,^[pqs]
would mean any file butp
,q
ors
。