如何只对匹配的正则表达式进行grep ?

时间:2022-01-12 06:13:36

I write in a file NotEmpty.txt all my non-empty text files in a directory dir with the following command:

我把文件写得乱七八糟。在目录下的所有非空文本文件中,使用以下命令:

find dir/ -not -empty -ls | grep -E "*.txt" > NotEmpty.txt

I'd like to print only the matching regex and not all the information on the line. How is it possible?

我只想打印匹配的正则表达式,而不是所有的信息。怎么可能?

2 个解决方案

#1


2  

The problem is that you are executing ls against every match, so the output contains a lot of stuff. Instead, use this find command to print the name.

问题是您对每个匹配执行ls,因此输出包含许多内容。相反,使用这个find命令来打印名称。

Note, in fact, that you can do everything in one shot, including selecting just .txt files:

注意,实际上,你可以一次完成所有的事情,包括选择仅仅.txt文件:

find your_dir/ -not -empty -name "*.txt" -print > NotEmpty.txt
#                          ^^^^^^^^^^^^^ ^^^^^^
#                                 |         |
#                          just .txt files  |
#                                           |
#                               print its name instead of `ls`ing it

You can also say -type f to just check files, which in fact I guess it is assumed by the -not -empty parameter.

你也可以说-type f来检查文件,实际上我猜它是由-not -empty参数假设的。

#2


1  

Use the -o parameter of grep to specify that you only want the matching portion.

使用grep的-o参数指定您只需要匹配的部分。

Example:

例子:

$ echo foo bar baz | grep -o "foo"
foo

#1


2  

The problem is that you are executing ls against every match, so the output contains a lot of stuff. Instead, use this find command to print the name.

问题是您对每个匹配执行ls,因此输出包含许多内容。相反,使用这个find命令来打印名称。

Note, in fact, that you can do everything in one shot, including selecting just .txt files:

注意,实际上,你可以一次完成所有的事情,包括选择仅仅.txt文件:

find your_dir/ -not -empty -name "*.txt" -print > NotEmpty.txt
#                          ^^^^^^^^^^^^^ ^^^^^^
#                                 |         |
#                          just .txt files  |
#                                           |
#                               print its name instead of `ls`ing it

You can also say -type f to just check files, which in fact I guess it is assumed by the -not -empty parameter.

你也可以说-type f来检查文件,实际上我猜它是由-not -empty参数假设的。

#2


1  

Use the -o parameter of grep to specify that you only want the matching portion.

使用grep的-o参数指定您只需要匹配的部分。

Example:

例子:

$ echo foo bar baz | grep -o "foo"
foo