I have a file with the following data in it:
adam
humanities
castiel
sciences
antwon
sciences
dmitri
informatics
zoe
mathematics
bernard
economics
I want to be able to sort the file w.r.t the names of the people so that the output looks like so:
adam
humanities
antwon
sciences
bernard
economics
castiel
sciences
dmitri
informatics
zoe
mathematics
cat filename | sort
sorts all the data including the subjects. How do I sort it with the names of people?
In the Linux system, you will find one command named sort. This command can sort your data alphabetically. Here flag -k is used to select a field for sorting.
The sort command is a command-line utility for sorting lines of text files. It supports sorting alphabetically, in reverse order, by number, by month, and can also remove duplicates.
The sort command sorts the contents of a file, in numeric or alphabetic order, and prints the results to standard output (usually the terminal screen). The original file is unaffected. The output of the sort command will then be stored in a file named newfilename in the current directory.
The easiest way to list files by name is simply to list them using the ls command. Listing files by name (alphanumeric order) is, after all, the default. You can choose the ls (no details) or ls -l (lots of details) to determine your view.
Using asorti in awk to sort the array of data
awk '{a[$1]=$2} END {n=asorti(a,c);for (i=1;i<=n;i++) print c[i] "\n" a[c[i]] "\n"}' RS= file
adam
humanities
antwon
sciences
bernard
economics
castiel
sciences
dmitri
informatics
zoe
mathematics
If your awk does not have asorti, try this:
awk '{print $1,$2}' RS="" file | sort | awk '{print $1 "\n" $2 "\n"}'
It is a quite brutal solution, but works... :) You can make it look better. The main idea is to create
<name>|<occupation>\n
list, and sort it than make it look as the original.
cat /tmp/delme | sed -e ':a;N;$!ba;s/\n/|/g' | sed -e 's/||/\n|/g' | sort | sed -e 's/|/\n/g'
Use awk - strip the empty lines and print each record separated by colon say. Then sort and then using awk print the record in the required format.
awk -v RS="" -F"\n" '{print $1 ":" $2}' e | sort | awk -v FS=":" '{print $1 "\n" $2 "\n"}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With