Thursday, January 31, 2008

AWK - Change field separator, add line number


Simple but useful. The sample file is "," delimited.

$ cat testfile.out
3232,32332,54545,34
3233,45645,23233,23
1211,1212,4343,434
3434,121121,121,33

If I have to change the field separator of the above file from "," to "|" (can also be done using 'tr') and have to add the line number as the first field. Then

$ awk 'BEGIN{FS=",";OFS="|"} {$1=$1; print NR,$0}' testfile.out
1|3232|32332|54545|34
2|3233|45645|23233|23
3|1211|1212|4343|434
4|3434|121121|121|33

4 comments:

Unknown said...

awk -F" " '{printf NR"|" } {gsub(/ /,"|",$0)}1' f1

dj said...

Hey nice solution, but what is the purpose of the $1=$1?

dj said...

What is the purpose of the $1=$1?

Unknown said...

perl -F, -lane 'BEGIN{$,="|"} print $., @F'

perl -p0777e 's/^/${\++$a},/mg; y/,/|/'

perl -pe '$_ = "$.|" . s/,/|/gr'

sed '=' | sed -e '$!N;y/\n,/||/'

© Jadu Saikia www.UNIXCL.com