1

I am writing my first unix bash script and I find it really difficult because I've never used linux before. It is homework from university. I tried a lot of stuff and I've been looking for hours but I simply can't find the right solution. Can someone give me some directions of what to use to sort strings from array which look like this:

room_100056.dat 4
room_8973.dat 2
room_7764.dat 1
room_2092.dat 20

to this:

room_7764.dat 1
room_8973.dat 2
room_10056.dat 4
room_2092.dat 20 

When sorting the initial array, I am creating a new array which contains the sorted data. The problem is that in the sorted array, the data is printed like this:

room_100056.dat 
room_8973.dat
room_7764.dat 
room_2092.dat
1
2
4
20

Code:

file=$1/*.dat

count_visits=()

for room in $file
do
   visits=$(grep "<Visit>" $room | wc -l)
   filename=$(basename $room)
   count_visits+=($filename$'\t'$visits)
done

sorted_visits=($(echo ${count_visits[@]} | tr " " "\n" | sort -g))
printf '%s\n' "${sorted_visits[@]}"
exit
3
  • You'll have bugs if your filenames have spaces unsell modifying count_visits+=( "$filename"$'\t'"$visits" ), and similarly quoting "$room". In general, you should probably run this code through shellcheck.net and follow its advice. Commented Feb 25, 2018 at 3:33
  • I will have a look, thank you very much! Commented Feb 25, 2018 at 13:37
  • (though actually, if you wanted everything to work right when filenames contain spaces, you'd put the number in the first column and the filename after it; that would also make it only sort -n needed, without the -k2). Commented Feb 25, 2018 at 17:27

1 Answer 1

2

Tell sort to use the second column numerically:

printf '%s\n' "${count_visits[@]}" | sort -k2n
Sign up to request clarification or add additional context in comments.

3 Comments

No reason not to make that printf '%s\n' "${count_visits[@]}" | sort -k2n and let the looping happen internally to printf.
@CharlesDuffy: I often forget about this functionality of printf. Thanks.
Thank you for the suggestion. This worked great! I will further investigate sort because I guess I've missed something.

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.