1

I have a text file for keeping game scores, the format is thus:

Name: score

Using a Bash script, I'm trying to place the names in one array and the scores in another. My first approach used the cut command:

names=(cut -d: -f1 ./scores.txt)
scores=(cut -d: -f2 ./scores.txt)

However, this approach didn't quite work because it would put all the names and scores in the very first entry in the array, which is inconvenient since I want to put the top five values in different variables and do a host of other things with them. I then tried using the following awk command:

names=(awk -F: '{ print $0 }' ./scores.txt)
scores=(awk -F: '{ print $1 }' ./scores.txt)

This did the exact same thing.

Does anyone have any suggestions on how to put all the parsed values in their own array element, or perhaps a completely different approach to efficiently store these values? Also, this has to be done in Bash for reasons.

2
  • Would it make sense to put them both into one associative array in which the index could be the name and the element could be the score?
    – jesse_b
    Commented Oct 27, 2017 at 21:46
  • That's not how you save the output into an array... With bash 4 use mapfile -t names < <( cut -d: -f1 scores.txt) ) and mapfile -t scores < <(cut -d: -f2 scores.txt | tr -d ' '). Commented Oct 27, 2017 at 22:16

1 Answer 1

0

Assuming your input file has every name/score combo on a newline this should do what you need:

while read line; do 
    names+=($(echo "$line" | awk '{print $1}' | tr -d ':'))
    scores+=($(echo "$line" | awk '{print $2}'))
done < "$INPUT_FILE"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .