The expert help needed please:
File1:
;1002 Desc1002
;1001 Desc1001
207 Desc207
205 Desc205
;6 Desc6
2010 Desc2010
;2011 Desc2011
Output should be sorted numerically:
;6 Desc6
205 Desc205
207 Desc207
;1001 Desc1001
;1002 Desc1002
2010 Desc2010
;2011 Desc2011
(If a character sort is easier to do, producing the following output, oh well... it'll do)
;1001 Desc1001
;1002 Desc1002
2010 Desc2010
;2011 Desc2011
205 Desc205
207 Desc207
;6 Desc6
Is it possible to insert leading zeros to the output? So the output would look like:
;000006 Desc6
000205 Desc205
000207 Desc207
;001001 Desc1001
;001002 Desc1002
002010 Desc2010
;002011 Desc2011
This might work for you:
sed 's/^;\?\([0-9]*\)/\1\t&/' file | sort -n | sed 's/.*\t//'
;6 Desc6
205 Desc205
207 Desc207
;1001 Desc1001
;1002 Desc1002
2010 Desc2010
;2011 Desc2011
awk -F";" '{print $1 $2 "|" $0}' fileName | sort -n | cut -d"|" -f2
You can insert leading zero's and keep the ; in play, like this:
awk '$1 ~ /^;/ ? sub(/^;/, "", $1) && $1 = ";"sprintf( "%06d", $1 ) : $1 = sprintf( "%06d", $1 )' file.txt
So to give you the desired output, (and if you don't mind two consecutive awk calls), you can quickly join it up with amit_g's answer:
awk '$1 ~ /^;/ ? sub(/^;/, "", $1) && $1 = ";"sprintf( "%06d", $1 ) : $1 = sprintf( "%06d", $1 )' file.txt | awk -F";" '{print $1 $2 "|" $0}' | sort -n | cut -d "|" -f 2
Output:
;000006 Desc6
000205 Desc205
000207 Desc207
;001001 Desc1001
;001002 Desc1002
002010 Desc2010
;002011 Desc2011
HTH