gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:19:36 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

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

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

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

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

或者,您可以使用 process substitution和一个 while 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)

关于bash - 如何使用 bash 脚本循环访问文件名中包含特定单词的目录中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11877704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com