Sujet : Re: Numerically sorted arguments (in shell)
De : chris (at) *nospam* x550c.mshome.net (Chris Elvidge)
Groupes : comp.unix.shellDate : 19. Jun 2024, 14:40:28
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v4ujjt$1vjpg$1@dont-email.me>
References : 1 2
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.2.1 Lightning/5.4
On 18/06/2024 at 18:04, Janis Papanagnou wrote:
I've just tried a Unix tools based solution (with sed, sort, cut).
Up to and including the line containing 'shuf' is data generation, the rest (starting with 'sed') extracts and sorts the data. I've written it for TWO numeric sort keys (see printf format specifier)
for (( i=1; i<=50; i++ )) do for (( j=2; j<=120; j+=3 )) do printf
"a%db%dc.txt\n" i j done done | shuf |
sed 's/[^0-9]*\([0-9]\+\)[^0-9]*\([0-9]\+\)[^0-9]*/\1\t\2\t&/' | sort
-t$'\t' -k1n -k2n | cut -f3-
For just one numeric argument this can be simplified (shorter sed pattern, simpler sort -n command), and for more than two numeric fields it can be modified to dynamically construct the sed pattern, the sort option list, and the cut parameter, once at the beginning; that way we could have a tool for arbitrary amounts of numeric keys in the file name.
Note: this program doesn't handle pathological filenames (newlines).
Janis
If you're happy not handling pathological filenames:
for (( i=1; i<=50; i++ )); do for (( j=2; j<=120; j+=3 )); do touch "a${i}b${j}c.txt"; done; done
to create the files.
exnums() { j="$(sed 's/[^[:digit:]]\+/ /g' <<<"$@")"; printf '%s%s\n' "$j" "$@"; }
function replaces all non-digit sequences with a space, prints digit sequence(s) and original input.
for i in *; do exnums "$i"; done | sort -k1n -k2n -k3n -k4n | awk '{print $NF}'
sort doesn't seem to care how many -k you use, fields separated with space.
awk prints the last field of the input.
This "seems" to work with all manner of filenames from PNN.htm (as your original sequence) to p323dc45g12.htm, p324dc45g12.htm, p333dc45g12.htm
Seems to work in ksh, too.
-- Chris Elvidge, EnglandTAR IS NOT A PLAYTHING