如何在Bash脚本中使用Awk搜索以外部指定字符串开头的字段?
Hey there! I can spot exactly what's tripping up your script—let's get it sorted while keeping your existing structure intact.
The Root Problem
Your current regex "aux*" is being interpreted by AWK as: match any string containing "au" followed by zero or more "x" characters—which is definitely not what you want when trying to match fields starting with your target letter. You're missing two key pieces: the start-of-string anchor (^) and correct variable interpolation in the regex.
The Fix
Modify the AWK regex to use the ^ anchor (which marks the start of the field) and properly reference your aux variable. Here's the corrected line for your loop:
echo $(cat "$1" | awk -v aux="$F" 'BEGIN{IGNORECASE=1;}{for(i=1;i<=NF;i++)if($i ~ "^" aux )print $i;}END{}')
Let me break down the key changes:
^tells AWK to only match the pattern if it occurs at the start of the field"^" auxconcatenates the anchor with yourauxvariable value (the current letter from your loop), so it checks if the field starts with that specific letter- I added quotes around
"$1"to handle filenames with spaces (a safe practice even if you don't plan for it now) - Swapped backticks
`for$()—it's more readable and avoids escaping issues in modern Bash
Optional (But Robust) Tweaks
While you asked to keep the core structure, these tiny adjustments won't change your logic but make the script more reliable:
- Wrap
$1in quotes everywhere:if test -f "$1"andecho "$1 is not a file" - You can eliminate the
catcommand entirely by passing the file directly to AWK (this is more efficient):echo $(awk -v aux="$F" 'BEGIN{IGNORECASE=1;}{for(i=1;i<=NF;i++)if($i ~ "^" aux )print $i;}' "$1")
With these changes, your loop will correctly output all fields starting with each letter (case-insensitive) from your input file, just like you intended.
内容的提问来源于stack exchange,提问作者Kreatives

