sidnow
February 16, 2016, 2:52pm
1
Hi,
I want to know how to place a particular field availble in a record as the columnname.
Name,Sam,Age,13,School, StJohn
Name,Rita,Age,12,School, StMichael,
Name,John,Age,14,School, StAnthony
I want the output as
Name Age School
Sam 13 StJohn
Rita 12 StMichael
John 14 StAnthony
I am not sure how to transpose with help of awk
Aia
February 16, 2016, 2:57pm
2
awk -F, 'BEGIN{print "Name","Age","School"}{print $2,$4,$6}' sidnow.file
1 Like
Hi try:
awk -F, 'NR==1{print $1,$3,$5}{print $2,$4,$6}' file
1 Like
sidnow
February 16, 2016, 3:04pm
4
Thanks for the reply guys, however forgot to mention, the number of columns are dynamic. As in it will not be Name, Age, School always. It can Name, Age, School, some other field etc.
How can I dynamically assign the odd numbered fields as the column name for the even numbered fields?
Try:
awk -F, '
NR==1 {
s=$1
for(i=3; i<=NF; i+=2) s=s OFS $i
print s
}
{
s=$2
for(i=4; i<=NF; i+=2) s=s OFS $i
print s
}
' file
Or with a function
awk -F, 'function prt(start){for (i=start; i<=NF-2; i+=2) printf "%s ",$i; print $i} NR==1 {prt(1)} {prt(2)}' file
RudiC
February 16, 2016, 7:24pm
7
awk -F, '
NR==1 {DL = ""
for (i=1; i<=NF; i+=2) {printf "%s%s", DL, $i
DL = FS
}
printf "\n"
}
{DL = ""
for (i=2; i<=NF; i+=2) {printf "%s%s", DL, $i
DL = FS
}
printf "\n"
}
' file
---------- Post updated at 01:23 ---------- Previous update was at 01:20 ----------
or, even better:
awk -F, '
NR==1 {for (i=1; i<NF; i+=2) printf "%s%s", $i, FS
printf "%s\n", $i
}
{for (i=2; i<NF; i+=2) printf "%s%s", $i, FS
printf "%s\n", $i
}
' file
---------- Post updated at 01:24 ---------- Previous update was at 01:23 ----------
Too late, MadeInGermany's function approach beats this clumsy one by far.