1

I'm writing a shell script traversing a list of directories and counting words from files inside them. The code prints data each time I read a file. So the output is not sorted. How can I sort it?

The output right now is like this:

cat 5
door 1
bird 3
dog 1

and I want to sort it first by second column and then by first column:

dog 1
door 1
bird 3
cat 5

2 Answers 2

1

You can pipe your shell script to:

sort -n -k2 -k1

With -n you specify numeric sort and with -k2 that you want to sort first by the second field and with -k1 to sort then by first field.

Sign up to request clarification or add additional context in comments.

3 Comments

I added many kind of sort pipe to end of my echo but nothing happens.
just echo "$name $count" . Is that important printing after each file search ?
you'll put this command not after each file search but when you are calling your shell script
0

First of all, I tried to reproduce what OP is doing, so after creating the files, I tried this command:

% for i in *; do echo -n "$i "; wc -w < $i; done
bird 3
cat 5
dog 1
door 1

Then I have added the sort:

 % (for i in *; do echo -n "$i "; wc -w < $i; done) | sort -n -k 2 -k 1    
dog 1
door 1
bird 3
cat 5

3 Comments

Just add -r to the sort for reverse sorting.
when I use -r the door comes before dog. I still want names in ascending order
@aykutyilmaz Try sort -k1 | sort -rnsk2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.