修改jq命令实现解析多JSON文件匹配正则时同步输出对应文件名
问题根因
你使用cat *.json将多个JSON文件的内容拼接后传入jq,此时jq仅能拿到合并后的纯JSON数据流,没有对应源文件的名称信息,因此无法将匹配结果和原文件关联。
调整后命令
直接输出每个命中文件的对应结果:
for file in *.json; do jq --arg filename "$file" '. as $data | [path(..| select(scalars and (tostring | test("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$", "ixn")))) ] | map({ (.|join(".")): (. as $path | .=$data | getpath($path)) }) | reduce .[] as $item ({}; . * $item) | if length > 0 then {($filename): .} else empty end' "$file" done
如果需要将所有结果合并为一个完整JSON输出,在命令末尾追加管道即可:
for file in *.json; do jq --arg filename "$file" '. as $data | [path(..| select(scalars and (tostring | test("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$", "ixn")))) ] | map({ (.|join(".")): (. as $path | .=$data | getpath($path)) }) | reduce .[] as $item ({}; . * $item) | if length > 0 then {($filename): .} else empty end' "$file" done | jq -s 'add'
调整说明
- 去掉了原逻辑中合并所有文件内容的
cat *.json,改用shell循环逐个处理每个JSON文件 - 通过jq的
--arg参数将当前处理的文件名传入jq内部作为变量 - 新增结果判断:仅当当前文件存在匹配结果时才输出内容,无匹配的文件不会产生冗余输出
- 输出结构保留了你原有的匹配路径+对应邮箱的格式,外层新增文件名作为一级key,可直接对应到源文件
内容的提问来源于stack exchange,提问作者swetha
相关产品推荐
相关产品推荐

