所以我有一个 bash 脚本,它应该从文本文件中打印人名和他们的分数
文本输入文件如下
Ted 86
Anthony 70
Mark 95
Kyle 65
David 75
这是我的代码#! /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 read line
do
lineArray=($line)
names+=(${lineArray[0]})
scores+=(${lineArray[1]})
done < $inputfile
echo "${names[@]} ${scores[@]}"
这是输出score is a file
Ted Anthony Mark Kyle David 86 70 95 65 75
我的问题是,我需要以与输入文本文件中相同的方式显示输出,但我不知道如何使用循环来执行此操作。谢谢
最佳答案
你可以做一个for
循环遍历两个数组中的条目。
#!/bin/bash
inputfile="$1"
if [[ ! -f $inputfile ]]; then
echo "$inputfile must be a file"
exit 1
else
echo "$inputfile is a file"
fi
names=()
scores=()
while IFS= read -r name score
do
names+=( "$name" )
scores+=( "$score" )
done < $inputfile
# like this:
for ((i=0; i<${#names[@]}; ++i))
do
echo "${names[$i]} ${scores[$i]}"
done
关于linux - 使用 bash 格式化在 shell 中打印的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64434661/