[英]How to use grep to match the files?
我正在尝试学习 RegEx,但这很难。
例如,我有 3 个文件:
$ ls
thisisnothing12.txt Thisisnothing12.txt thisisnothing.txt
我想使用 ls 到 grep 只输出带有数字的 2 个文件。这些是我尝试过的,但它们甚至没有显示单个文件。为什么? 他们怎么了?
$ ls | grep "^[\w]+[\d]+\.[\w]{3}$"
$ ls | grep "^[a-zA-Z]+[0-9]+\.[a-zA-Z]{3}$"
谢谢。
有不同的正则表达式风格,请参阅https://stackoverflow.com/a/66256100/7475450
如果要使用\d
,则需要使用 PCRE :
$ 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
^[\w]+[\d]+\.[\w]{3}$
^[a-zA-Z]+[0-9]+\.[a-zA-Z]{3}$
让我们简化一下。 它们本质上是相同的,因为[\w]
与\w
相同,即[A-Za-z]
。 和\d
一样。
所以我们可以简化为
^\w+\d+\.\w{3}$
问题是^
断言字符串的开头,而$
是结尾。 grep
适用于每一行。 并且ls
在一行上返回所有结果。 您可以使用ls -1
每行获取一个文件。 您还需要 grep 的-P
标志才能使用\w
和\d
。
$ ls -1 | grep -P "^\w+\d+\.\w{3}$"
您可以在这里尝试不同的正则表达式: https://regexr.com/5mujo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.