【发布时间】:2020-10-21 15:28:08
【问题描述】:
我正在尝试使用冒泡排序在 bash 中按字典顺序对名称列表及其分数进行排序。数组是
Ted 86
Anthony 70
Mark 95
Kyle 65
David 75
名称存储在数组names中,分数存储在数组scores中
这是我的代码,它在第 30 行给了我一个错误,说“对许多参数”,我似乎找不到原因。
#! /bin/bash
inputfile="$1"
if [[ !(-f "$1") ]]; then
echo "$1 must be a file"
exit 1
else
echo "$1 is a file"
fi
names=()
scores=()
while IFS= read -r name score
do
names+=( "$name" )
scores+=( "$score" )
done < $inputfile
echo "The arrays before sorting"
for (( i=0; i<${#names[@]}; ++i ))
do
echo "${names[$i]} ${scores[$i]}"
done
echo "The sorted arrays using bubble sort"
for (( i = 0; i < ${#names[@]}; i++ ))
do
for (( j = $i; j < ${#names[@]}; j++ ))
do
if [ ${names[$i]} -gt ${names[$j]} ]; then #error here
t=${names[$i]}
names[$i]=${names[$j]}
names[$j]=$t
fi
done
done
for (( i=o; i<${#names[@]}; ++i ))
do
echo "${names[$i]}"
done
谁能复制粘贴看看他们是否遇到同样的问题?
【问题讨论】:
-
好的,我将 IFS= 替换为 IFS= " ",现在两个数组都已填充。排序相同的错误:(@KamilCuk
标签: linux bash shell command-line