我想打印第二列中包含两个字符的所有文件名。我怎么能用awk做到这一点?
aa.txt文件
REM A 7 35.32
REM A 8 47.17
REM B 9 988.62
REM D 10 111.59
BB.txt
REM A 7 135.32
REM A 8 647.19
REM B 9 88.62
CC.txt
REM A 7 135.32
REM A 8 247.17
REM B 9 188.62
REM B 10 111.56
期望的输出
BB.txt
CC.txt
您的建议将不胜感激!!
答案 0 :(得分:3)
for i in *.txt; do
if [ $(awk '{ print $2 }' $i | sort -u | wc -l) -eq 2 ]; then
echo $i
fi
done
答案 1 :(得分:2)
仅使用GNU awk
的一种方式:
awk '
## A function that prints the file name if only found two different strings
## in the second field.
function check_col_and_print_file(c, i) {
if ( length(c) == 2 ) {
printf "%s\n", ARGV[ i ];
}
}
## At the beginning of each file but the first one, call the function to
## check if the file must be printed, and reset the array for the processing
## of the next file (the current one because we already are in first line).
FNR == 1 && NR > 1 {
check_col_and_print_file(cols, ARGIND-1);
delete cols;
}
## Save second field as a key of a hash to avoid repeated values.
{
cols[ $2 ] = 1;
}
## Same as before but in the "END" block because we finished the processing
## of all input files.
END {
check_col_and_print_file(cols, ARGIND);
}
' AA.txt BB.txt CC.txt
产量:
BB.txt
CC.txt