Bash 如何将行的第一部分保存在列表/数组中,然后根据第二部分对它们进行排序?
我有一个学校项目,它给了我几行字符串,文本如下:Bash 如何将行的第一部分保存在列表/数组中,然后根据第二部分对它们进行排序?,bash,Bash,我有一个学校项目,它给了我几行字符串,文本如下: 团队1-2:2-1 团队3-1:2-2 等 它希望我确定哪支球队获胜(或平局),然后和他们一起制作一个排行榜,为胜利/平局打分 这是我第一次使用bash。我所做的是将team1/team2名称保存在一个变量中,然后对目标执行相同的操作。我该怎么做桌子?我设法让我的脚本创建一个新文件,将所有团队名称保存在其中(并检查是否存在重复项),但我不知道如何继续。我是否应该为每个团队制作一个数组,并在其中保存他们的结果?例如,我如何实施排名 第1组3p
- 团队1-2:2-1
- 团队3-1:2-2
- 等
- 第1组3p
- 团队2 1p
- 等等
awk
输入文件:scores.txt
team1-team2:2-1
team3-team1:2-2
代码:
awk -F'[:-]' ' # set delimiters to ':' or '-'
{
if($3>$4){teams[$1] += 3} # first team gets 3 points
else if ($3<$4){teams[$2] += 3} # second team gets 3 points
else {teams[$1]+=1; teams[$2]+=1} # both teams get 1 point
}
END{ # after scanning input file
for(team in teams){
print(team OFS teams[team]) # print total points per team
}
}' scores.txt | sort -rnk 2 > ranking.txt # sort by nb of points
我会用这个
AWK是一种解释性编程语言(AWK代表Aho、Weinberger、Kernighan),设计用于文本处理,通常用作数据提取和报告工具。AWK主要用于Unix系统
对于这类工作,使用纯bash脚本通常很麻烦
让我向您展示一下使用awk
输入文件:scores.txt
team1-team2:2-1
team3-team1:2-2
代码:
awk -F'[:-]' ' # set delimiters to ':' or '-'
{
if($3>$4){teams[$1] += 3} # first team gets 3 points
else if ($3<$4){teams[$2] += 3} # second team gets 3 points
else {teams[$1]+=1; teams[$2]+=1} # both teams get 1 point
}
END{ # after scanning input file
for(team in teams){
print(team OFS teams[team]) # print total points per team
}
}' scores.txt | sort -rnk 2 > ranking.txt # sort by nb of points
问题可分为三个部分:
#!/bin/bash
declare -A results
while IFS=':-' read team1 team2 score1 score2; do
if [ ${score1} -gt ${score2} ]; then
((results[${team1}]+=2))
elif [ ...next test... ]; then
...
else
...
fi
done < scores.txt
# Now you have an associative array containing the points for each team.
# You can either output it as it stands, or sort it by piping through the
# 'sort' command.
for key in $[!results[@]}; do
echo ...
done
#/bin/bash
声明-A结果
当IFS=':-'读取team1 team2 score1 score2;做
如果[${score1}-gt${score2}];然后
((结果[${team1}]+=2))
elif[…下一个测试…];然后
...
其他的
...
fi
完成
问题可分为三个部分:
#!/bin/bash
declare -A results
while IFS=':-' read team1 team2 score1 score2; do
if [ ${score1} -gt ${score2} ]; then
((results[${team1}]+=2))
elif [ ...next test... ]; then
...
else
...
fi
done < scores.txt
# Now you have an associative array containing the points for each team.
# You can either output it as it stands, or sort it by piping through the
# 'sort' command.
for key in $[!results[@]}; do
echo ...
done
!/bin/bash
声明-A结果
当IFS=':-'读取team1 team2 score1 score2;执行
如果[${score1}-gt${score2}];则
((结果[${team1}]+=2))
elif[…下一个测试…];然后
...
其他的
...
fi
完成
根据您的实现方式,在检查重复项时,如果发现重复项,您可以添加一个逻辑来求和分数?并保存它,然后根据分数进行排序。您可以使用管道|
在poi为每个步骤编写单独的bash脚本,该脚本根据您的实现方式从上一个脚本获取输入为了检查重复项,如果发现重复项,您可以添加一个逻辑来求和分数,然后保存它,然后根据分数进行排序。您可以使用pipe|
为每个步骤编写单独的bash脚本,这些脚本从前面的脚本中获取输入良好的解释有助于选择任何工具良好的解释有助于选择任何工具你选择