Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort with multiple lines in bash?

I am trying to sort a list of names followed by another string such as:

John Doe
AVAIL

Sara Doe
CALL

Jim Doe
AVAIL

I am trying to sort these by name but can't seem to figure it out with sort. Can someone provide some guidance?

My final output would look like this:

Jim Doe
AVAIL

John Doe
AVAIL

Sara Doe
CALL

Much appreciated!

like image 311
Tristan Lanford Avatar asked Jul 03 '12 17:07

Tristan Lanford


People also ask

How do I sort lines in Linux?

To sort lines of text files, we use the sort command in the Linux system. The sort command is used to prints the lines of its input or concatenation of all files listed in its argument list in sorted order. The operation of sorting is done based on one or more sort keys extracted from each line of input.

How do I sort files in bash?

Bash Sort Files Alphabetically By default, the ls command lists files in ascending order. To reverse the sorting order, pass the -r flag to the ls -l command, like this: ls -lr . Passing the -r flag to the ls -l command applies to other examples in this tutorial.

How do I sort multiple files in Linux?

Another way to sort multiple files simultaneously is to pipe the find command output to sort and use the --files0-from= option in the sort command. Specify the -print0 option in find to end file name with the NUL character and ensure the program properly reads the file list.

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.


1 Answers

Probably far from optimal, but

sed -r ':r;/(^|\n)$/!{$!{N;br}};s/\n/\v/g' names | sort | sed 's/\v/\n/g'

seems to do the job (names is the file with records). This allows records of arbitrary length, not just 2 lines.

like image 175
Lev Levitsky Avatar answered Oct 05 '22 18:10

Lev Levitsky