Monday 23 July 2018

Sort strings in numeric order based on unpadded numbers appearing at a set position in the string

Sort strings in numeric order based on unpadded numbers appearing at a set position in the string
Was setting up catch all Apache redirects for moved content and needed the numeric IDs sorted in descending order, so rules where numeric ID of one is a subset of another (e.g. /news/pr/10 and /news/pr/100 and /news/pr/1000) all get processed correctly. The sort command makes this super easy.
$ cat test
/path/to/old/100/?(.*) /path/to/new/8494830/
/path/to/old/101/?(.*) /path/to/new/2894822/
/path/to/old/10/?(.*) /path/to/new/8494835/
/path/to/old/999/?(.*) /path/to/new/2551975/
/path/to/old/110/?(.*) /path/to/new/1294833/
/path/to/old/990/?(.*) /path/to/new/2494234/
/path/to/old/9/?(.*) /path/to/new/9594831/
/path/to/old/99/?(.*) /path/to/new/4194836/
/path/to/old/90/?(.*) /path/to/new/9294838/
/path/to/old/1000/?(.*) /path/to/new/3498564/
/path/to/old/1/?(.*) /path/to/new/1496534/
The following tells the sort command to use forward slash as the field delimiter (-t), look at column 5 (-k5), sort that column numerically (n), in reverse (r):
$ sort -t/ -k5nr test
/path/to/old/1000/?(.*) /path/to/new/3498564/
/path/to/old/999/?(.*) /path/to/new/2551975/
/path/to/old/990/?(.*) /path/to/new/2494234/
/path/to/old/110/?(.*) /path/to/new/1294833/
/path/to/old/101/?(.*) /path/to/new/2894822/
/path/to/old/100/?(.*) /path/to/new/8494830/
/path/to/old/99/?(.*) /path/to/new/4194836/
/path/to/old/90/?(.*) /path/to/new/9294838/
/path/to/old/10/?(.*) /path/to/new/8494835/
/path/to/old/9/?(.*) /path/to/new/9594831/
/path/to/old/1/?(.*) /path/to/new/1496534/

0 comments:

Post a Comment