Monday 17 September 2012

Awk substitute and concatenate columns

Using Awk


awk -F, '{ sub($1,"");temp = $3"."$4; $2 = temp; print}' myfile.csv

set delimiter as comma, then removes column 1 sub from "", takes column 3 and 4 and concatenates with a full stop in between them, and puts that in column 2


This was used so i could take a name in a file with a first and last name and create a username like joe.bloggs


Another useful Awk feature is sub strings


awk -F, '{ sub($1,"");temp = $3"."$4; $2 = temp; first= substr($3,1,1); second = substr($4,1,1); $5=first second  ; print}' myfile.csv

substr($3,1,1) takes first char of column 3 puts it in variable first
substr($4,1,1) takes first char of column 4 puts it in variable second
$5 = first second prints these 2 chars together, no spaces

Use on Joe Bloggs to create new column  with contents - JB


This used the substr function

Every good boy.

awk '{print substr($1,1,1)}' temp returns E
awk '{print substr($1,3)}' temp returns ery
awk '{print substr($2,3)}' temp returns od
awk '{print substr($0,7,2)}' temp returns go
 
 






No comments:

Post a Comment