linux - 使用 bash 格式化在 shell 中打印的数组

标签 linux bash shell ubuntu command-line

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

相关文章:

c - 在 linux 上写入映射内存时使用 mmap 返回共享内存

Linux 上低磁盘空间条件下的 Java 属性文件

linux - (bash) 如何找到文件系统支持的最大文件大小?

python - 访问 python json key 时需要传递参数

bash - 引用 shell 变量的打印

bash - awk 提取列但仅从一行中提取

bash - 在 Bash 脚本中将字符串作为命令运行

c++ - 使用 mmap 时性能下降

linux - 关闭期望脚本而不关闭ssh中的 session

php - 在linux中使用php创建txt文件