关于AWK的一个问题!如何对文件分组进行统计?!见补充问题

2025-05-15 22:55:45
推荐回答(3个)
回答1:

用shell脚本。

#!/bin/bash
myfile="1.txt"
touch tmp
while read line
do
info=`echo "$line"|awk '{print $2}'`
grep "$info" tmp >/dev/null 2>&1
if [ $? -eq 0 ]; then
num=`awk '{print $NF}' tmp`
num=`expr $num + 1`
sed -i "s/^\($info\t\)[0-9]*$/\1$num/" tmp
else
echo "$line"|awk '{print $2"\t"1}' >>tmp
fi
done <$myfile
exit 0

只需从头到尾遍历文件一次。与下面链接里的问题类似。
——————————————————————————————————
楼上shuguangbo的方法非常简洁,学习了!

回答2:

相当于数据库 group by。先标记一下 回来研究 三楼 shuguangbo 高手!

回答3:

awk '{ w[$2]+=1} END{ for (a in w) print a, w[a]}' 1.txt