如何对目录中的所有文件执行grep操作

时间:2023-01-14 23:30:40

Working with xenserver, and I want to perform a command on each file that is in a directory, grepping some stuff out of the output of the command and appending it in a file.

使用xenserver,我想对目录中的每个文件执行一个命令,从命令的输出中提取一些内容并将其附加到一个文件中。

I'm clear on the command I want to use and how to grep out string(s) as needed.

我很清楚要使用的命令以及如何根据需要提取字符串。

But what I'm not clear on is how do I have it perform this command on each file, going to the next, until no more files are found.

但我不清楚的是,我如何让它在每个文件上执行这个命令,直到找到更多的文件为止。

4 个解决方案

#1


146  

grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.

grep模式*美元就足够了。默认情况下,grep会跳过所有子目录。然而,如果你想通过他们,grep grep - r模式*美元。

#2


72  

In Linux, I normally use this command to recursively grep for a particular text within a dir

在Linux中,我通常使用这个命令递归地为目录中的特定文本设置grep

grep -rni "string" *

where,

在那里,

r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search

r =递归我。e,在当前目录n =中搜索子目录,将行号打印到stdout i =大小写不敏感搜索

#3


22  

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

使用find。认真地说,这是最好的方法,因为这样你就能真正看到它在运行什么文件:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

注意,-H是特定于mac的,它在结果中显示文件名。

#4


2  

If you want to do multiple commands, you could use:

如果您想要执行多个命令,可以使用:

for I in `ls *.sql`
do
    grep "foo" $I >> foo.log
    grep "bar" $I >> bar.log
done

#1


146  

grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.

grep模式*美元就足够了。默认情况下,grep会跳过所有子目录。然而,如果你想通过他们,grep grep - r模式*美元。

#2


72  

In Linux, I normally use this command to recursively grep for a particular text within a dir

在Linux中,我通常使用这个命令递归地为目录中的特定文本设置grep

grep -rni "string" *

where,

在那里,

r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search

r =递归我。e,在当前目录n =中搜索子目录,将行号打印到stdout i =大小写不敏感搜索

#3


22  

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

使用find。认真地说,这是最好的方法,因为这样你就能真正看到它在运行什么文件:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

注意,-H是特定于mac的,它在结果中显示文件名。

#4


2  

If you want to do multiple commands, you could use:

如果您想要执行多个命令,可以使用:

for I in `ls *.sql`
do
    grep "foo" $I >> foo.log
    grep "bar" $I >> bar.log
done