使用 grep 列出文件?

Mah*_*ass 7 command-line bash grep ls

我有一个包含以下文件的目录:

file1a file1ab file12A2 file1Ab file1ab
Run Code Online (Sandbox Code Playgroud)

我想列出所有file1以两个字母开头并后跟最多两个字母的文件!

我提出的解决方案如下:

ls | grep -i file1 [az] {2}
Run Code Online (Sandbox Code Playgroud)

但它不起作用!

我想知道为什么?以及如何列出?

hee*_*ayl 11

您不需要管道,grepls. 只需使用shell globbing。

在 中bash,使用extglob模式(应该在交互会话中默认启用,如果不这样做shopt -s extglob先设置它):

file1@(|?|??)
Run Code Online (Sandbox Code Playgroud)

?匹配任何单个字符,@(||)选择以|.分隔的任何模式。

如果您只想匹配a-z和之间的任何字符A-Z,请使用[:alpha:]表示当前语言环境中所有字母字符的字符类:

file1@(|[[:alpha:]]|[[:alpha:]][[:alpha:]])
Run Code Online (Sandbox Code Playgroud)

例子:

$ ls -1
file1
file112
file11a
file12A2
file1a
file1ab
file1Ab
file1as
file2
fileadb

$ ls -1 file1@(|[[:alpha:]]|[[:alpha:]][[:alpha:]]))
file1
file1a
file1ab
file1Ab
file1as
Run Code Online (Sandbox Code Playgroud)

zsh 原生支持这个:

file1(|[[:alpha:]]|[[:alpha:]][[:alpha:]])
Run Code Online (Sandbox Code Playgroud)

应 OP 的要求,我非常不情愿地回答了这一部分。

任何未来的读者,不要解析ls,使用通配符。

使用lsgrep

ls | grep -E '^file1[[:alpha:]]{,2}$'
Run Code Online (Sandbox Code Playgroud)

例子:

% ls | grep -E '^file1[[:alpha:]]{,2}$'
file1
file1a
file1ab
file1Ab
file1as
Run Code Online (Sandbox Code Playgroud)