关于egrep提取特定关键字的输出格式调整需求
Got it, let's figure out how to adjust your egrep command's output to match your expected format. First, a quick note: your original command has a tiny syntax hiccup — the ** before the pattern is unnecessary (probably a typo), so the base working command should be:
egrep -i 'pid|material|behavior=m' test.inc
Below are common formatting tweaks based on typical use cases. Pick the one that fits your needs, or let me know if you have a specific output layout in mind!
1. Extract & Align Specific Fields
If you want to pull out only the pid, material, and behavior=m key-value pairs from matching lines and align them neatly:
egrep -i 'pid|material|behavior=m' test.inc | awk '{ for (i=1; i<=NF; i++) { if ($i ~ /^pid=/ || $i ~ /^material=/ || $i ~ /^behavior=m/) { printf "%-18s ", $i # Adjust the number to control column width } } print "" }'
This will left-align each matched field in an 18-character column, making the output clean and easy to scan.
2. Group Output by Keyword
If you want all pid lines grouped together, followed by material lines, then behavior=m lines:
# Simple sorting approach egrep -i 'pid|material|behavior=m' test.inc | sort -k1,1 -f # More structured grouped output with headers awk ' /pid/i { pid_lines = pid_lines $0 "\n" } /material/i { mat_lines = mat_lines $0 "\n" } /behavior=m/i { beh_lines = beh_lines $0 "\n" } END { print "=== PID Entries ===" print pid_lines print "=== Material Entries ===" print mat_lines print "=== Behavior=m Entries ===" print beh_lines } ' test.inc
The second option adds clear section headers for better readability.
3. Only Show Matching Keyword Parts (No Extra Line Content)
If you don't need the entire line, just the exact pid=..., material=..., or behavior=m... matches:
egrep -io 'pid=[^[:space:]]+|material=[^[:space:]]+|behavior=m[^[:space:]]*' test.inc
The -o flag tells egrep to output only the matched parts, and [^[:space:]]+ grabs everything until the next space.
4. Format as CSV (For Spreadsheets)
If you need the output in comma-separated values to import into a table:
awk -v OFS="," ' /pid|material|behavior=m/i { pid = ""; mat = ""; beh = "" for (i=1; i<=NF; i++) { if ($i ~ /^pid=/i) pid = substr($i, 5) # Strip "pid=" from the start else if ($i ~ /^material=/i) mat = substr($i, 10) # Strip "material=" else if ($i ~ /^behavior=m/i) beh = substr($i, 11) # Strip "behavior=m" } print pid, mat, beh } ' test.inc
This will create a CSV where each row has the corresponding pid, material, and behavior values (empty fields stay blank).
内容的提问来源于stack exchange,提问作者Nayak

