0

so I have a bash script that is supposed to print peoples names and their scores from a text file

The text input file is as follows

Ted 86 
Anthony 70
Mark 95
Kyle 65
David 75

This is my code

#! /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[@]}" 

This is the output

score is a file
Ted Anthony Mark Kyle David 86 70 95 65 75

My issue is, I need the output to be displayed in the same way as it appears in the input text file and I don't know how to use a loop to do it. Thank you

1
  • Isn't it obvious that you should use a loop? Commented Oct 19, 2020 at 21:31

1 Answer 1

1

You could make a for loop to loop over the entries in the two arrays.

#!/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
Sign up to request clarification or add additional context in comments.

1 Comment

Consider quoting, as in names+=( "$name" ). If someone names themselves *, we don't want to add a list of filenames in the current directory to the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.