Sort a text file, a (possible) leading ";" should be ignored, but retained in the output

Go To StackoverFlow.com

1

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

2012-04-04 22:40
by Sacha_ITWorks
What have you tried?Dan Fego 2012-04-04 22:55


2

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
2012-04-04 22:51
by potong
It works! Great :) Thanks - Sacha_ITWorks 2012-04-04 23:14


2

awk -F";" '{print $1 $2 "|" $0}' fileName | sort -n | cut -d"|" -f2
2012-04-04 22:52
by amit_g
+1 nice, clean on - icyrock.com 2012-04-04 22:57
@amit_g Thanks! It works great - Sacha_ITWorks 2012-04-04 23:14


0

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

2012-04-05 03:44
by Steve
Ads