使用存储在文件中的 golb 模式进行搜索 - bash
Use golb patterns stored in a file for searching - bash
如何使用存储在文本文件中的 glob 模式作为文件搜索的输入?
我想在所有子目录中搜索与存储在文本文件中的全局模式匹配的文件。
具有全局模式的文件如下所示:
/Dongle/src/*.c
/App/files/**/*.xml
...
谁可以将该文件用作 bash 中 find
命令的输入?
到目前为止我尝试的是:
modelFile=
root="Project/"
regexes=$(cat $modelFile)
outFile="out.txt"
for re in $regexes; do
find $root -type f -regex $re > $outFile
done
但是没有匹配到任何文件。如果我像这样使用它,它会起作用:
(...)
for re in $regexes; do
find $root -type f -regex "/App/files/**/*.xml" > $outFile
done
for re in $regexes; do
find $root -type f -regex "/Dongle/src/*.c " >> $outFile
done
我不一定非得用find
。其他每个 bash 命令也可以工作。
输出应该是匹配 glob 模式的每个文件。
这些不是正则表达式,这些是 glob 模式。
此外,find
不会很有效地找到匹配项,因为模式本身应该可以直接由 shell 解析,
如果您的 shell 支持 globstar
和 nullglob
扩展。
shopt -s globstar nullglob
while read glob; do
for path in $glob; do
echo "$path"
done
done < "$modelFile" > "$outFile"
您的原始代码的其他一些重要问题:
- 在循环中使用
>
重定向到同一个文件会在每次迭代时覆盖该文件
- 始终将用作命令行参数的变量括在双引号中
- 使用 while 循环而不是 for 循环逐行处理输入
如何使用存储在文本文件中的 glob 模式作为文件搜索的输入?
我想在所有子目录中搜索与存储在文本文件中的全局模式匹配的文件。 具有全局模式的文件如下所示:
/Dongle/src/*.c
/App/files/**/*.xml
...
谁可以将该文件用作 bash 中 find
命令的输入?
到目前为止我尝试的是:
modelFile=
root="Project/"
regexes=$(cat $modelFile)
outFile="out.txt"
for re in $regexes; do
find $root -type f -regex $re > $outFile
done
但是没有匹配到任何文件。如果我像这样使用它,它会起作用:
(...)
for re in $regexes; do
find $root -type f -regex "/App/files/**/*.xml" > $outFile
done
for re in $regexes; do
find $root -type f -regex "/Dongle/src/*.c " >> $outFile
done
我不一定非得用find
。其他每个 bash 命令也可以工作。
输出应该是匹配 glob 模式的每个文件。
这些不是正则表达式,这些是 glob 模式。
此外,find
不会很有效地找到匹配项,因为模式本身应该可以直接由 shell 解析,
如果您的 shell 支持 globstar
和 nullglob
扩展。
shopt -s globstar nullglob
while read glob; do
for path in $glob; do
echo "$path"
done
done < "$modelFile" > "$outFile"
您的原始代码的其他一些重要问题:
- 在循环中使用
>
重定向到同一个文件会在每次迭代时覆盖该文件 - 始终将用作命令行参数的变量括在双引号中
- 使用 while 循环而不是 for 循环逐行处理输入