3

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.

Nate
  • 30,286
  • 23
  • 113
  • 184
barlop
  • 12,887
  • 8
  • 80
  • 109

3 Answers3

6
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.

Erik
  • 88,732
  • 13
  • 198
  • 189
  • for anybody not aware, the printf part gets the hex value of the 'line' converted to decimal and at the beginning of the line. so they can then be sorted . the output at that point is two columns and awk of course gets the second column giving the file sorted. very nice. A printf example $ echo a| printf "%d %s\n" "0xa" "a" <-- prints `10 a` – barlop Feb 11 '14 at 21:36
0

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.

mohit6up
  • 4,088
  • 3
  • 17
  • 12
  • fails with $ echo -e '1FFF\nF000\nc' | sort -n 'cos that example the one with more Fs is treated as larger by sort -n. Maybe it just converts each char on the line to an ascii number and adds them. Not taking into account their position. – barlop Feb 16 '11 at 19:11
  • It's not an easy thing to check.. but you could've been more apprehensive of that option working to sort hex, knowing that it doesn't mention it, and if it works via ascii, then if it does work for hex, it's a mathematical accident. so maybe as a comment with a question mark.. or an apprehensive answer. – barlop Feb 16 '11 at 19:36
  • oh I don't know about etiquette – barlop Feb 16 '11 at 19:50
0

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.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351