Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting alphabetically in Bash

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?

like image 706
rahuL Avatar asked Aug 22 '13 07:08

rahuL


People also ask

How do I sort alphabetically in Shell?

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.

How do I sort a line alphabetically in Linux?

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.

How do I sort alphabetically in Unix?

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.

How do I list alphabetically in Linux?

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.


3 Answers

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"}'
like image 158
Jotne Avatar answered Nov 15 '22 07:11

Jotne


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'
like image 40
csikos.balint Avatar answered Nov 15 '22 09:11

csikos.balint


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"}'
like image 39
suspectus Avatar answered Nov 15 '22 08:11

suspectus