5

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?

4

5 回答 5

6

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"}'
于 2013-08-22T08:08:40.633 回答
2

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'
于 2013-08-22T08:02:05.780 回答
2

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"}'
于 2013-08-22T08:11:06.600 回答
1

This might work for you (GNU sed):

sed '/./!d;$!N;s/\n/ /' file | sort | sed 's/ /\n/g;$!G'

Drop blank lines. Read two lines into the pattern space. Replace newline with space. Sort file. The replace the newlines and add in blank lines.

于 2013-08-22T08:00:03.047 回答
0

Not pretty and won't work if your names contain spaces...you probably want a perl solution to do this in a sane and readable way.

$ awk -v RS='\n\n' '{ print $1, $2 }' foo.input | sort | sed -e 's#$#\n#g' -e 's# #\n#g'
adam
humanities

antwon
sciences

bernard
economics

castiel
sciences

dmitri
informatics

zoe
mathematics
于 2013-08-22T07:58:30.247 回答