首页 > 解决方案 > 如何使用 grep 匹配文件?

问题描述

我正在尝试学习 RegEx,但这很难。

例如,我有 3 个文件:

$ ls
thisisnothing12.txt  Thisisnothing12.txt  thisisnothing.txt

我想使用 ls 来仅 grep 出带有数字的 2 个文件。这些是我尝试过的,但它们甚至没有显示单个文件。为什么?em 有什么问题?

$ ls | grep "^[\w]+[\d]+\.[\w]{3}$"
$ ls | grep "^[a-zA-Z]+[0-9]+\.[a-zA-Z]{3}$"

谢谢。

标签: grep

解决方案


有不同的正则表达式风格,请参阅https://stackoverflow.com/a/66256100/7475450

如果要使用,则需要使用 PCRE \d

$ touch thisisnothing12.txt  Thisisnothing12.txt  thisisnothing.txt
$ ls
Thisisnothing12.txt  thisisnothing.txt  thisisnothing12.txt
$ ls | grep '\d'    # '\d' does not work in POSIX Basic regex
$ ls | grep -P '\d' # use PCRE regex
Thisisnothing12.txt
thisisnothing12.txt
$

如您所见,您可以只搜索您感兴趣的字符。

您可以缩小范围,例如查找以数字开头的文件:

$ touch 2feet.txt
$ ls | grep -P '\d'
2feet.txt
Thisisnothing12.txt
thisisnothing12.txt
$ ls | grep -P '^\d'
2feet.txt
$

通过本教程了解更多信息:https ://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex


推荐阅读