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.

  • 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 Oct 27 '17 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 ' '). – don_crissti Oct 27 '17 at 22:16
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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.