sorting and reversing lines of a file

Leo de Wit leo at philmds.UUCP
Fri Jan 27 22:24:22 AEST 1989


In article <9056 at burdvax.PRC.Unisys.COM> lang at pearl.PRC.Unisys.COM (Francois-Michel Lang) writes:
|
|I need utilities to do two things:
|(1) reverse the order of lines in a file
|    but leave the lines themselves intact.
|    The Unix utility does just the opposite of this.
|
|    E.g., if the file "f" contains
|       line1 
|       line2
|       line3
|    I want to produce
|       line 3
|       line 2
|       line 1
|    I have an awk program to do this,
|    but I'm sure some clever soul out there can do much better.

tail -r f

|(2) sort a file by length of input lines.
|    Again, I have a script to do this which uses awk, sort, and sed,
|    but I'm sure it can be done better.

Don't know if this is better; at least it is different (8-):

#! /bin/sh
# Usage: lensort [files]

sed '
h
s/./Z/g
G
s/\n/A/' $* |
sort|
sed 's/^Z*A//'

The trick used here is to prepend each line with a copy of itself with
all characters substituted by a 'Z' and terminated by a A; lexically
sorting will thus be done in order of line lengths (e.g. ZZZApqr comes
before ZZZZAabcd). Afterwards the Z*A prefixes are removed by sed.

|I'd prefer no C programs!
Sorry about tail -f (8-).

|Many thanks.
Hope it helped,
                 Leo.



More information about the Comp.unix.questions mailing list