Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Moving Data from a Column to a Row/String

Status
Not open for further replies.

danhodges99

IS-IT--Management
Feb 6, 2003
21
GB
Hi all,

I have a file with several columns of data, eg:

A B C D
--- --- --- ---
1 2 5 1
2 2 2 2
8 4 4 4
4 2 3 4
10 9 4 4
9 7 1 2

I need to get the values from, say, column B and place them into a string separated by a semicolon, eg:

2;2;4;2;9;7

Does anyone have any ideas how to do this? Any help would be massively appreciated! Thanks.
 
something like that:

nawk -v colID="B" -f getCol.awk text.txt
nawk -v colID="D" -f getCol.awk text.txt

#----------------------- getCol.awk
BEGIN {
OFS=";"

if (colID=="") colID="A";

FLDheader="1"
FLDskip="2"
}

NR == FLDheader {
for(i=1; i <= NF; i++)
if ($i == colID) {
colNum=i
break;
}
if (colNum == &quot;0&quot;) {
printf(&quot;Warning: couldn't find column [%s]\n&quot;, colID) | &quot;cat 1>&2&quot;
exit 1;
}
next;
}

NR != FLDskip {
row = (length(row)) ? row OFS $colNum : $colNum;
}

END {
if (colNum != 0)
print row;
}


vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
or better yet - to skip 'empty' lines. This produced an undesired extra ';' you're posting about in your other thread in this forum.

BEGIN {
OFS=&quot;;&quot;

if (colID==&quot;&quot;) colID=&quot;A&quot;;
colNum=&quot;0&quot;

FLDheader=&quot;1&quot;
FLDskip=&quot;2&quot;
}

NR == FLDheader {
for(i=1; i <= NF; i++)
if ($i == colID) {
colNum=i
break;
}
if (colNum == &quot;0&quot;) {
printf(&quot;Warning: couldn't find column [%s]\n&quot;, colID) | &quot;cat 1>&2&quot;
exit 1;
}
next;
}

NR != FLDskip && NF >= colNum {
row = (length(row)) ? row OFS $colNum : $colNum;
}

END {
if (colNum != 0)
print row;
}




vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top