Question

If I have a file of hex numbers of different length e.g.

1F
b
c

How can I sort them from the command line?

Linux solutions are welcome, though I'll be using windows and cygwin or gnuwin32.

Note: I clearly can't use SORT 'cos that will keep them in that order which is wrong.

Was it helpful?

Solution

cat thefile | while read line; do printf "%d %s\n" "0x$line" "$line"; done | sort -n | awk '{print $2}'

This retains the original upper/lower case of the hexadecimal numbers.

OTHER TIPS

You could use an awk script to create a file that left-pads the strings to a fixed length, sort the resulting file, and then strip leading spaces on the result.

It's been a while since I used awk, but as I recall it wasn't difficult to output things right-justified.

Try sort -n filename. The -n flag as per the man page "compare according to string numerical value".

Update: as pointed out by @barlop, the -n option does not work for hex numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top