bash - 是否可以在bash脚本中剪切特定列并显示该列重复出现的次数?

标签 bash shell unix scripting

文本文件:

Bill Both, 123456789, Computer Information Systems
Carla Carothers, 234567890, Computer Information Systems 
Stephanie Williams, 345678901, Marketing
Aritrya Badopadhi, 456789012, Computer Science
Santhi Roopashree, 567890123, Computer Information Systems
Heather Williams, 678901234, Computer Information Systems
Dave Schroth, 789012345, Computer Science

我想要的输出是:

4 Computer Information Systems
2 Computer Science
1 Marketing

-- 这是我的脚本

file=$1
for line in $(cat $file)
do
        echo "$line" | cut -d " "  -f4-6 | uniq -d 
done
exit 0

但它没有向我显示第 4 列中重复出现的情况。

最佳答案

编辑2:现在根据OP的评论添加 shell 解决方案。

FIELD=3
DELMITER=","
cut -d$DELMITER -f $FIELD Input_file | sort| uniq -c |sort -nr

其中变量 FIELD 将具有字段编号值,DELIMITER 中具有分隔符的值,在本例中为 ,(取决于您的数据文件)。Input_file 是您在此处阅读的数据文件。



编辑:您可以尝试以下操作吗?这将以排序的方式提供输出。

awk '
BEGIN{
  FS=","
}
{
  a[$NF]++
}
END{
  for(i in a){
    print a[i],i
  }
}' Input_file  | sort -k2

输出如下。

4  Computer Information Systems
2  Computer Science
1  Marketing


如果您想以与 Input_file 中最后一个字段相同的顺序获取输出,请尝试以下操作。

awk '
BEGIN{
  FS=","
}
!b[$NF]++{
  c[++count]=$NF
}
{
  a[$NF]++
}
END{
  for(i=1;i<=count;i++){
    print a[c[i]],c[i]
  }
}' Input_file

关于bash - 是否可以在bash脚本中剪切特定列并显示该列重复出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230156/

相关文章:

linux历史命令

string - 用于替换文件夹中每个文件中字符串的所有实例的 Unix 命令

bash - 如何使用 sed(或 awk)进行链接规范化,获取文件名?

bash - 如何使用 bash 脚本在远程 Linux 服务器上运行多个命令

linux - 如何使用 bash 脚本检查 "{"是否在 java 文件的单独行中开始

bash - grep 从屏幕输出并分离

将结构定义压缩为一行并使用 sed 制作两个副本

c - Unix信号如何工作?

unix - 连接多个文件,但包含文件名作为节标题

linux - 如何将参数传递给 Bash 脚本?