如何在一个文件夹中的所有文件中递归地搜索元数据中的关键字?



我需要从一个位置递归地搜索所有子目录和文件,并打印出包含与我指定的任何关键字匹配的元数据的任何文件。

。如果John Smith在元数据中被列为hello.js的作者,并且我的关键字之一是' John ',我希望脚本打印hello.js

我认为解决方案可以是mdls的组合grep和但是我没有使用bash很久以前,所以我有点卡住了。

我尝试了下面的命令,但这只打印关键字所在的行,如果'john'找到。

mdls hello.js | grep john

提前感谢。

(作为参考,我使用macOS)

mdls的输出管道输出到grep中,如您在问题中所示,不会将文件名向前转。下面的脚本递归地遍历所选目录中的文件,并检查其中一个属性是否与所需模式匹配(使用regex)。如果是,则输出文件名。

#!/bin/bash
shopt -s globstar    # expand ** recursively
shopt -s nocasematch # ignore case
pattern="john"
attrib=Author
for file in /Users/me/myfiles/**/*.js
do
attrib_value=$(mdls -name "$attrib" "$file")
if [[ $attrib_value =~ $pattern ]]
then
printf 'Pattern: %s found in file $filen' "$pattern" "$file"
fi
done

您可以使用文字测试而不是正则表达式:

if [[ $attrib_value == *$pattern* ]]

为了使用globstar,您需要使用比MacOS默认安装的Bash版本更高的Bash版本。如果这是不可能的,那么您可以使用find,但是在处理包含换行符的文件名时存在一些挑战。这个脚本负责这个。

#!/bin/bash
shopt -s nocasematch # ignore case
dir=/Users/me/myfiles/
check_file () {
local attrib=$1
local pattern=$2
local file=$3
local attrib_value=$(mdls -name "$attrib" "$file")
if [[ $attrib_value =~ $pattern ]]
then
printf 'Pattern: %s found in file $filen' "$pattern" "$file"
fi
}
export -f check_file
pattern="john"
attrib=Author
find "$dir" -name '*.js' -print0 | xargs -0 -I {} bash -c 'check_file "$attrib" "$pattern" "{}"'

最新更新