sort hex numbers of different length from the command line?

橙三吉。 提交于 2020-01-04 04:33:08

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5020656/sort-hex-numbers-of-different-length-from-the-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!