【问题标题】:How to loop through files in a directory having a certain word in filename using bash script?如何使用bash脚本遍历文件名中包含特定单词的目录中的文件?
【发布时间】:2012-08-09 06:14:19
【问题描述】:

我正在尝试使用 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 

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

【问题讨论】:

  • 正确的语法应该是 for file in $(ls | grep 'my_word'); do,但使用 find 或 glob` 仍然是正确的方法。
  • 是的,谢谢,后来在史蒂夫的回答的帮助下想通了:)

标签: bash loops


【解决方案1】:

您应该尽可能avoid parsing ls。假设您的当前目录中没有子目录,通常一个 glob 就足够了:

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

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

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

或者,如果您的文件名包含特殊字符,请尝试:

find . -type f -name "*foo*" -print0 | xargs -0 cat

或者,您可以使用process substitutionwhile loop

while IFS= read -r myfile; do echo "$myfile"; done < <(find . -type f -name '*foo*')

或者,如果您的文件名包含特殊字符,请尝试:

while IFS= read -r -d '' myfile; do
  echo "$myfile"
done < <(find . -type f -name '*foo*' -print0)

【讨论】:

  • 感谢第一个作品。我如何在 for 循环中使用第二个?这就是我不知道的。我想用函数结果代替 *.
  • 想通了,files=find . -type f -name "*my_word*" | xargs cat 和 $files 中的文件有效!谢谢!
  • @SenthilKumar:很高兴我能帮上忙 :-)
  • @Steve no-parsing-ls 是安全问题吗?文件/目录名称可能是一个将所有内容发送到遗忘的命令?
  • @t0mgs:我不会称之为安全问题。解析任何输入时都存在这些问题。应该尽可能避免解析ls,因为输出并不总是可信的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-06
  • 2013-01-27
  • 2020-05-16
  • 2022-01-21
  • 2014-10-02
  • 1970-01-01
  • 2017-09-29
相关资源
最近更新 更多