一种相当通用的方法,使用awk
:
awk 'FNR==NR { array[$1]++; next } { for (i=1; i<=NF; i++) if ($i in array) print $0 }' dict file
解释:
FNR==NR { } ## FNR is number of records relative to the current input file.
## NR is the total number of records.
## So this statement simply means `while we're reading the 1st file
## called dict; do ...`
array[$1]++; ## Add the first column ($1) to an array called `array`.
## I could use $0 (the whole line) here, but since you have said
## that there will only be one integer per line, I decided to use
## $1 (it strips leading and lagging whitespace; if any)
next ## process the next line in `dict`
for (i=1; i<=NF; i++) ## loop through each column in `file`
if ($i in array) ## if one of these columns can be found in the array
print $0 ## print the whole line out
使用 bash 循环处理多个文件:
## This will process files; like file, file1, file2, file3 ...
## And create output files like, file.out, file1.out, file2.out, file3.out ...
for j in file*; do awk -v FILE=$j.out 'FNR==NR { array[$1]++; next } { for (i=1; i<=NF; i++) if ($i in array) print $0 > FILE }' dict $j; done
如果您有兴趣在tee
多个文件上使用,您可能想尝试这样的事情:
for j in file*; do awk -v FILE=$j.out 'FNR==NR { array[$1]++; next } { for (i=1; i<=NF; i++) if ($i in array) { print $0 > FILE; print FILENAME, $0 } }' dict $j; done 2>&1 | tee output
这将向您显示正在处理的文件的名称和找到的匹配记录,并将“日志”写入名为output
.