使用 grep 和 ls -a 命令

新手上路,请多包涵

使用 ls –agrep ,您将如何使用单个 grep 命令列出 /usr 中以字母 p 或字母 r 或字母 s 开头的所有文件的名称?

这是对的吗?

 ls –a | grep [prs] /usr

原文由 Nicole Romain 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 461
1 个回答
 ls -a /usr | grep '^[prs]'

将从 r ls -a /usr p 输出中选择以 /usr 84250f95d1f2b2f8ffd45726c2c58 中的任何一个开头的行 ---s 字符。

这可能是您的老师所期望的,但这是错误的,或者至少不可靠。

文件名可以由多行组成,因为换行符与 Linux 或任何 unix 上的文件名中的任何字符一样有效。 So that command doesn’t return the files whose name starts with p , q or s , but the lines of the filenames that start with p , qs 。通常,您不能可靠地对 ls 的输出进行后处理。

-a 是包含隐藏文件,即名称以 . 开头的文件。由于您只想要以 pqs 的那些,那是多余的。

注意:

 ls /usr | grep ^[pqs]

会更加错误。 First ^ is a special character in a few shells like the Bourne shell, rc , es or zsh -o extendedglob (though OK in bash 或其他 POSIX shell)。

然后,在大多数 shell 中( fish 是一个明显的例外), [pqs] 是一个通配符。这意味着 ^[qps] 旨在由 shell 扩展为与该模式匹配的文件列表(相对于当前目录)。

因此,在那些像 bash 这样的 shell 中,它们不会特别处理 ^ ,如果当前目录中有一个名为 ^p 的文件,那将变为

ls /usr | grep ^p

If there’s no matching file, in csh , tcsh , zsh or bash -O failglob , you’ll get an error message and the command will被取消。 In zsh -o extendedglob where ^ is a globbing operator, ^[pqs] would mean any file but p , q or s

原文由 Stephane Chazelas 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏