如何修改AWK命令实现多文件全列匹配指定字符串?
Fixing the Awk Command to Match Any Column Instead of Just Column 3
Got it, let's tweak that awk command so it checks every column for matches against your find.txt entries, not just the third one. Here's how to do it:
Modified Command
awk 'NR==FNR{a[$1];next} {for(i=1;i<=NF;i++) if($i in a) {print; next}}' find.txt path_to_100_files/*
Breakdown of the Changes
Let's walk through what's different from your original command:
- The first part
NR==FNR{a[$1];next}stays exactly the same: it reads all entries fromfind.txtinto an arraya(using each line as a key), then skips to the next line so we don't processfind.txtwith the second block. - The second block
{for(i=1;i<=NF;i++) if($i in a) {print; next}}does the heavy lifting:for(i=1;i<=NF;i++)loops through every column in the current line (NF is awk's built-in variable for "number of fields" in the line).if($i in a)checks if the current column's value exists in ourfind.txtarray.{print; next}prints the entire line as soon as we find a match, then moves to the next line (this prevents duplicate prints if multiple columns in the same line match entries fromfind.txt).
Optional: Matching Substrings (If Needed)
If you need to match entries from find.txt as substrings (e.g., match exa against example or exa123), you can adjust the command to use index() instead:
awk 'NR==FNR{a[$1];next} {for(i=1;i<=NF;i++) for(k in a) if(index($i,k)) {print; next}}' find.txt path_to_100_files/*
This loops through every key in the a array and checks if it's a substring of any column in the current line.
Example Behavior
Using your sample data:
find.txthas entries likeexample1,example 2,exa- A target file has lines with
example(column 1),example.com(column 5)- The first modified command will print lines where any column is exactly
exa(but notexample, since that's not an exact match forexa). - The substring version will print lines where any column contains
exa(so it would catchexampleandexa123).
- The first modified command will print lines where any column is exactly
内容的提问来源于stack exchange,提问作者proxadv
相关产品推荐
相关产品推荐

