【问题标题】:Formatting an array being printed in the shell using bash使用 bash 格式化在 shell 中打印的数组
【发布时间】:2020-10-19 20:23:44
【问题描述】:

所以我有一个 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

我的问题是,我需要以与输入文本文件中相同的方式显示输出,但我不知道如何使用循环来执行此操作。谢谢

【问题讨论】:

  • 应该使用循环不是很明显吗?

标签: linux bash shell ubuntu command-line


【解决方案1】:

您可以创建一个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

【讨论】:

  • 考虑引用,如names+=( "$name" )。如果有人将自己命名为*,我们不想将当前目录中的文件名列表添加到数组中。
猜你喜欢
  • 2013-01-31
  • 1970-01-01
  • 2021-05-03
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多