适配awk 3.1.7的日志敏感数据(邮箱/手机号/SSN)掩码脚本求助
I’ve dealt with similar compatibility headaches between awk versions before, so let’s fix this for your 3.1.7 environment. The core issue is that your original script uses Extended Regular Expression (ERE) features (like interval quantifiers {6,} and ungrouped parentheses ()) that aren’t supported by default in older awk versions—they rely on Basic Regular Expressions (BRE) instead.
Here are two reliable approaches, depending on whether your awk build supports the --re-interval flag:
Option 1: Use --re-interval (if available)
Some builds of awk 3.1.7 include the --re-interval flag to enable ERE-style interval quantifiers. If this works in your environment, you just need to adjust the regex to use BRE-compliant grouping (escape parentheses with \) and fix the escaped dot:
# Test with sample string echo "123-123-432-123-999-889 and 123456 and 1234-1234-4321-1234 and xyz@abc.com" | awk --re-interval 'gsub(/[0-9]{6,}|\([0-9]{3,}\.\){3,}|[[:alnum:]_]{2,}@[[:alnum:]_]{2,}\.[[:alnum:]_]{2,}/, "****") 1' # Process a file awk --re-interval 'gsub(/[0-9]{6,}|\([0-9]{3,}\.\){3,}|[[:alnum:]_]{2,}@[[:alnum:]_]{2,}\.[[:alnum:]_]{2,}/, "****") 1' sample.log
Key adjustments here:
- Escaped parentheses
\(and\)to define groups (BRE requires this for grouping, unlike ERE) - Escaped the dot
\.in the email pattern (dots are literal in regex unless escaped) - Used
[[:alnum:]_]instead of\wfor better compatibility (some older awk versions don’t recognize\w)
Option 2: BRE-only syntax (no flags required)
If --re-interval isn’t available, we need to rewrite the regex without interval quantifiers like {6,} or {3,}. We’ll explicitly repeat patterns to match the same logic:
# Test with sample string echo "123-123-432-123-999-889 and 123456 and 1234-1234-4321-1234 and xyz@abc.com" | awk 'gsub(/[0-9][0-9][0-9][0-9][0-9][0-9][0-9]*|\([0-9][0-9][0-9]\.\)\{3\}\([0-9][0-9][0-9]\.\)*|[[:alnum:]_][[:alnum:]_]*@[[:alnum:]_][[:alnum:]_]*\.[[:alnum:]_][[:alnum:]_]*/, "****") 1' # Process a file awk 'gsub(/[0-9][0-9][0-9][0-9][0-9][0-9][0-9]*|\([0-9][0-9][0-9]\.\)\{3\}\([0-9][0-9][0-9]\.\)*|[[:alnum:]_][[:alnum:]_]*@[[:alnum:]_][[:alnum:]_]*\.[[:alnum:]_][[:alnum:]_]*/, "****") 1' sample.log
Breakdown of the BRE regex:
- 6+ digits:
[0-9][0-9][0-9][0-9][0-9][0-9][0-9]*matches 6 mandatory digits followed by any number of additional digits - 3+ repetitions of
xxx.:\([0-9][0-9][0-9]\.\)\{3\}\([0-9][0-9][0-9]\.\)*matches 3 mandatory groups of 3 digits + dot, followed by any number of additional groups - Email addresses:
[[:alnum:]_][[:alnum:]_]*@[[:alnum:]_][[:alnum:]_]*\.[[:alnum:]_][[:alnum:]_]*matches at least 2 characters before@, at least 2 in the domain, and at least 2 in the TLD (using[[:alnum:]_]for letters, numbers, and underscores)
Both options will produce your desired output:
**** and **** and **** and ****
内容的提问来源于stack exchange,提问作者Chandre Gowda

