Showing posts with label sort. Show all posts
Showing posts with label sort. Show all posts

Saturday, May 15, 2010

Sort on a field

empfile
12345,Mary J,HR
34512,J Smith,Admin
34700,A Ryan,Admin
34900,B Wilson,HR
59000,C Diaz,HR

We want to sort the empfile by department (3rd field)

$sort -t, -k3 empfile
34512,J Smith,Admin
34700,A Ryan,Admin
12345,Mary J,HR
34900,B Wilson,HR
59000,C Diaz,HR

Option -t is to indicate field separator which here is comma
Option -k is the key indicating the position to sort on

Saturday, May 8, 2010

Count vowels in a file and order by count descending

$ cat vowelfile
this
that
these

$ grep -io [aeiou] vowelfile | uniq -c | sort -rk1
2 e
1 i
1 a

This has three parts:

grep -io
-i ignores the case and -o prints just the part of the string it matches. So it will just list a, e, i, o or u instead of printing the complete line with vowel.

$ grep -io [aeiou] vowelfile
i
a
e
e

uniq -c
Counts the number of unique lines in the grep output.
$ grep -io [aeiou] vowelfile | uniq -c
1 i
1 a
2 e

sort -rk1
sort with option -r reverses the default sort order, which is ascending. By default sort is on the entire line. Option -k allows us to specify the field number to sort on. In the example the first field is the count and the second field is the vowel.


And to get the total counts of the vowel:
grep -io [aeiou] vowelfile | wc -l
wc with -l does the count on lines

Took the basic code from here
http://www.geekinterview.com/question_details/55489