如何使用bash脚本循环遍历文件名中包含特定单词的目录中的文件?

问题描述:

我想通过bash脚本遍历包含文件名中某个单词的目录中的所有文件。如何使用bash脚本循环遍历文件名中包含特定单词的目录中的文件?

以下脚本遍历目录中的所有文件,

cd path/to/directory 

for file in * 
do 
    echo $file 
done 

ls | grep 'my_word'只给已在文件名中的单词“my_word”的文件。但是我不确定如何用ls替换*脚本中的grep'my_word'。

如果我不喜欢这个,

for file in ls | grep 'my_word' 
do 
    echo $file 
done 

它给了我一个错误“附近意外的标记'语法错误|'”。这样做的正确方法是什么?

+1

正确的语法是'在$文件(LS | grep '可以my_word');做',但使用'find'或者glob'仍然是正确的选择。 – chepner 2012-08-09 11:59:06

+0

是的,谢谢,后来在史蒂夫的回答帮助下计算出来:) – 2012-08-09 13:28:03

你永远不应该解析ls。假设没有子目录,也许这是你在找什么:

for file in *my_word*; do echo "$file"; done 

编辑:

如果您有多个子目录,您可能需要使用find。例如,为了cat文件:

find . -type f -name "*my_word*" | xargs cat 

或者,你可以尝试:

for file in $(find . -type f -name "*my_word*"); do echo "$file"; done 
+0

感谢第一个作品。我如何使用循环中的第二个?那是我不知道的。我想用*代替函数结果。 – 2012-08-09 06:31:40

+0

算出来了,files ='find。 -type f -name“* my_word *”| xargs猫“和$文件中的文件的作品!谢谢! – 2012-08-09 06:36:25

+0

@SenthilKumar:很高兴我能帮忙:-) – Steve 2012-08-09 06:41:11