目标:将每个.c程序的名称打印在由包含某个单词的第一个参数指定的目录中。
我的想法是:
word = "word"
for file in specifiedDirectory with c file extension
do
if grep -w $word $file ; then
echo $file
fi
done
答案 0 :(得分:3)
如果你有GNU grep
,你也可以这样做
grep -rwl --include '*.c' word specifiedDirectory
使用man page
中的相关选项-r, --recursive
Read all files under each directory, recursively, following symbolic links only if they are on the command line.
This is equivalent to the -d recurse option.
-w, --word-regexp
Select only those lines containing matches that form whole words. The test is that the matching substring must
either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be
either at the end of the line or followed by a non-word constituent character. Word-constituent characters are
letters, digits, and the underscore.
-l, --files-with-matches
Suppress normal output; instead print the name of each input file from which output would normally have been
printed. The scanning will stop on the first match. (-l is specified by POSIX.)
--include=GLOB
Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).
答案 1 :(得分:1)
通过现代发现,以下内容可以满足您的需求。
wordfind() {
find "$1" -name '*.c' -exec grep -wl word {} \+
}
您还可以吐出所有文件并使用xargs
来减少grep
需要运行的次数。
像这样。
wordfind() {
find "$1" -name '*.c' -print0 | xargs -0 -r grep -wl word
}
在上述任一函数中使用"$@"
代替"$1"
,以支持将多个目录传递给函数而不只是一个目录。 (还增加了对提供任意参数的支持,但这完全是另一个主题。)
答案 2 :(得分:1)
shopt -s globstar
word="word"
for file in path/to/**/*.c
do
grep -l -w "$word" "$file"
done
注意:
为了避免令人不快的意外,请始终将shell变量(如word
或file
)放在双引号中,如上所示。 Tnis防止分词。
使用-l
选项,grep
将打印任何匹配文件的名称。这使得if
和echo
语句不再必要。
为了搜索整个目录树,我们使用bash的globstar
功能。这使**/
能够匹配零个或多个目录。 (在Mac OSX上,除非您已升级到bash
4.0或更高版本,否则此功能不可用。)
在bash
赋值语句中,等号的两边不能有空格。我们来看看bash
如何看待这一行:
word = "word"
当bash
解释该行时,它将尝试使用两个参数执行命令word
:=
和word
。如果这不是您想要的,则必须删除空格。
grep
将在其命令行上接受多个文件名。因此,不需要for
循环:
shopt -s globstar
word="word"
grep -l -w "$word" path/to/**/*.c
假设我们要将脚本作为./word someDirectory
运行,并让它在someDirectory
树中搜索c
文件。在脚本中,第一个参数可以引用为$1
。因此,创建一个名为goto
的文件,其执行位设置为chmod +x word
),内容为:
#!/bin/bash
shopt -s globstar
word="word"
for file in "$1"/**/*.c
do
grep -l -w "$word" "$file"
done
同样简化版本:
#!/bin/bash
shopt -s globstar
word="word"
grep -l -w "$word" "$1"/**/*.c