如何在Bash中使用grep查找无tag字段的digest值
Hey there! Since you can't use jq or Python, we can absolutely solve this with just grep. Here are a couple of practical approaches:
Two-step grep pipeline (most portable)
This works with standard grep implementations and doesn't rely on advanced regex features:
grep -o '\{"digest":[^}]+\}' your_file.json | grep -v '"tag"' | grep -o '"digest": "\K[^"]+'
Let's break this down:
- The first grep extracts each individual object from the IDS array that has a
digestfield (grabs everything from{"digest":up to the closing}). - The second grep filters out any objects that include a
tagfield. - The third grep pulls out just the digest value by matching everything after
"digest": "until the next quote mark.
This will output each digest on its own line. If you can sneak in a tiny tool like tr to join them into space-separated values (even though you mentioned no other tools), you could add | tr '\n' ' ' to the end—but if not, the newline output is fully functional.
Single grep command (uses PCRE)
If your grep supports the -P flag (common in GNU grep), you can do it in one line with a more advanced regex:
grep -oP '"digest": "\K[^"]+(?=(?:(?!tag)[^}])*\})' your_file.json
Here's what this does:
-Penables Perl-compatible regex, which lets us use lookarounds."digest": "\Kmatches the literal"digest": "but discards it from the output (so we only get the digest value).[^"]+captures the actual digest string (all characters except a quote).- The lookahead
(?=(?:(?!tag)[^}])*\})makes sure that between the end of the digest and the closing}of the object, there's no"tag"present.
This also outputs each digest on a new line.
内容的提问来源于stack exchange,提问作者dpa456

