如何仅匹配匹配的正则表达式?
How to grep only the matching regex?
我在文件 NotEmpty.txt 中使用以下命令将所有非空文本文件写入目录 dir :
find dir/ -not -empty -ls | grep -E "*.txt" > NotEmpty.txt
我只想打印匹配的正则表达式,而不是该行的所有信息。怎么可能?
问题是您要针对每个匹配项执行 ls
,因此输出包含很多内容。相反,使用此 find
命令打印名称。
请注意,事实上,您可以一次完成所有操作,包括只选择 .txt
个文件:
find your_dir/ -not -empty -name "*.txt" -print > NotEmpty.txt
# ^^^^^^^^^^^^^ ^^^^^^
# | |
# just .txt files |
# |
# print its name instead of `ls`ing it
你也可以说 -type f
只检查文件,实际上我猜这是由 -not -empty
参数假定的。
使用 grep 的 -o
参数指定您只需要匹配的部分。
示例:
$ echo foo bar baz | grep -o "foo"
foo
我在文件 NotEmpty.txt 中使用以下命令将所有非空文本文件写入目录 dir :
find dir/ -not -empty -ls | grep -E "*.txt" > NotEmpty.txt
我只想打印匹配的正则表达式,而不是该行的所有信息。怎么可能?
问题是您要针对每个匹配项执行 ls
,因此输出包含很多内容。相反,使用此 find
命令打印名称。
请注意,事实上,您可以一次完成所有操作,包括只选择 .txt
个文件:
find your_dir/ -not -empty -name "*.txt" -print > NotEmpty.txt
# ^^^^^^^^^^^^^ ^^^^^^
# | |
# just .txt files |
# |
# print its name instead of `ls`ing it
你也可以说 -type f
只检查文件,实际上我猜这是由 -not -empty
参数假定的。
使用 grep 的 -o
参数指定您只需要匹配的部分。
示例:
$ echo foo bar baz | grep -o "foo"
foo