SHELL10. 第二列是否有重复
描述
给定一个 nowcoder.txt文件,其中有3列信息,如下实例,编写一个shell脚本来检查文件第二列是否有重复,且有几个重复,并提取出重复的行的第二列信息:Bash 解法, 执行用时: 2ms, 内存消耗: 416KB, 提交时间: 2021-09-24
declare -A arr while read line do temparr=($line) arr[${temparr[1]}]=$((${arr[${temparr[1]}]}+1)) done for key in ${!arr[@]} do if [[ ${arr[$key]} -gt 1 ]] then echo ${arr[$key]}" "$key fi done
Bash 解法, 执行用时: 3ms, 内存消耗: 376KB, 提交时间: 2021-06-16
#!/bin/bash # awk '{a[$2]++}END{for(i in a){if (a[i]>1) {print a[i],i}}}' nowcoder.txt unset map declare -A map while read line do j=(${line[@]}) i=${j[1]} if [[ -z ${map[$i]} ]];then map[$i]=1 else ((map[$i]++)) fi done < nowcoder.txt mm=() for i in ${!map[@]} do if [ ${map[$i]} -gt 1 ];then # echo ${map[$i]} $i mm[${#mm[@]}]=${map[$i]} fi done for (( i=0;i<${#mm[@]};i++ )) do for (( j=$[$i+1];j<${#mm[@]};j++ )) do if [ ${mm[i]} -gt ${mm[j]} ];then tmp=${mm[i]} mm[i]=${mm[j]} mm[j]=$tmp fi done done for (( i=0;i<${#mm[@]};i++ )) do for j in ${!map[@]} do if [ ${map[$j]} -eq ${mm[$i]} ];then echo ${map[$j]} $j fi done done
Bash 解法, 执行用时: 3ms, 内存消耗: 376KB, 提交时间: 2021-04-18
# awk '{a[$2]++}END{for(i in a){if (a[i]>1) {print a[i],i}}}' nowcoder.txt unset map declare -A map while read line do j=(${line[@]}) i=${j[1]} if [[ -z ${map[$i]} ]];then map[$i]=1 else ((map[$i]++)) fi done < nowcoder.txt mm=() for i in ${!map[@]} do if [ ${map[$i]} -gt 1 ];then # echo ${map[$i]} $i mm[${#mm[@]}]=${map[$i]} fi done for (( i=0;i<${#mm[@]};i++ )) do for (( j=$[$i+1];j<${#mm[@]};j++ )) do if [ ${mm[i]} -gt ${mm[j]} ];then tmp=${mm[i]} mm[i]=${mm[j]} mm[j]=$tmp fi done done for (( i=0;i<${#mm[@]};i++ )) do for j in ${!map[@]} do if [ ${map[$j]} -eq ${mm[$i]} ];then echo ${map[$j]} $j fi done done
Bash 解法, 执行用时: 3ms, 内存消耗: 384KB, 提交时间: 2021-05-12
declare -A map while read line do j=(${line[@]}) i=${j[1]} if [[ -z ${map[$i]} ]];then map[$i]=1 else ((map[$i]++)) fi done < nowcoder.txt mm=() for i in ${!map[@]} do if [ ${map[$i]} -gt 1 ];then mm[${#mm[@]}]=${map[$i]} fi done for ((i=0;i<${#mm[@]};i++)) do for ((j=$[$i+1];j<${#mm[@]};j++)) do if [ ${mm[i]} -gt ${mm[j]} ];then temp=${mm[i]} mm[i]=${mm[j]} mm[j]=$temp fi done done for ((i=0;i<${#mm[@]};i++)) do for j in ${!map[@]} do if [ ${map[$j]} -eq ${mm[$i]} ];then echo ${map[$j]} $j fi done done
Bash 解法, 执行用时: 3ms, 内存消耗: 408KB, 提交时间: 2021-12-27
declare -A map while read line do arr=(${line}) i=${arr[1]} if [ -z ${map[$i]} ] then map[$i]=1 else ((map[$i]++)) fi done < nowcoder.txt for i in ${!map[@]} do if [ ${map[$i]} -gt 1 ] then echo ${map[$i]} $i fi done