在目录和子目录中循环遍历所有匹配模式的文件。

huangapple go评论54阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月11日 01:44:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定