英文:
sh loop for all files in a directory and sub-directories matching a pattern
问题
我想循环遍历与某种模式匹配的文件。它们可以在当前目录或子目录中。
我尝试了:
for file in **/$_pat*; do
但它只能找到子目录中的文件。我还将以下命令放入bashrc
和脚本中,但仍然不起作用。
shopt -s globstar
shopt
在脚本中无法识别。
shopt: not found
英文:
I want to loop through files matching a pattern. They can be in the current directory or sub directories.
I tried:
for file in **/$_pat*; do
but it only finds files in sub directories. I also put the following command in bashrc
and also in the script but it still doesn't work.
shopt -s globstar
shopt
isn't recognized in the script.
shopt: not found
答案1
得分: 1
使用 find
命令:
find "$_path" -type f -iname "*your_pattern*"
其中:
-iname
= 对模式进行不区分大小写的匹配
-type f
= 仅搜索常规文件,省略目录或链接
在循环中使用它:
find "$_path" -type f -iname "*your_pattern*" | while read file
do
echo "$file"
done
如果搜索结果中有空格,for
循环将不起作用,而 while
循环会逐行读取每个结果
根据您的最终目标,您可以在 find
中使用 -exec
,例如:
find "$_path" -type f -iname "*your_pattern*" -exec echo {} \;
其中 {}
会代表匹配的行/文件
同时在末尾确实需要使用 \;
。
英文:
Use find
:
find "$_path" -type f -iname "*your_pattern*"
Where:
-iname
= case insensitive matching of a pattern
-type f
= searches only regular files, omitting directories or links
To use it in a loop:
find "$_path" -type f -iname "*your_pattern*"|while read file
do
echo "$file"
done
for
loop will not work if you have spaces in the results, while while
reads each while line
Depending on what you want to do a an end goal, you can use the -exec in find like:
find "$_path" -type f -iname "*your_pattern*" -exec echo {} \;
where {}
would represent the matching line/file`
Also you do ned the \;
at the end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论