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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

split one column into four 1

Status
Not open for further replies.

steco

Technical User
Dec 7, 2006
5
SE
Hi,
Im new to awk and would be very grateful if you could help with the following. I have a number of data files with the following format

x
1
2
3
y
4
5
6
z
7
8
9
vel
2
3
4

and I would like to split them into 4 columns and save the output to new files as:
1 4 7 2
2 5 8 3
3 6 9 4

The nr. of values between x,y,z and vel can vary from file to file but within the same file there are always as many x's as there are y's z's and vel's.
 
Does it absolutely have to be awk? A better solution is break your input into files of 1 column each and then paste the files together. No error checking:

Code:
#!/bin/ksh

rm -f tmpfile.*

while read line
do
   if [[ "$line" = "x" || "$line" = "y" || "$line" = "z" || "$line" = "vel" ]]
   then
      file="tmpfile.""$line"
      continue
   fi
   echo "$line" >> $file

done < data.file
# Now, build your output
paste -d" " tmpfile.*
 
An awk solution:

Code:
awk '
    /[a-z]/{row=0;next}
    {a[row++]=a[row] $1 OFS }
    END{for (row in a) {print a[row]}}
' inputfile

Annihilannic.
 
Thanks olded, your ksh script works fine.
Annihilannic, your awk gives the following output:

3 6 9 4
1 4 7 2
2 5 8 3

Is there any way to sort the columns, so that I get:

1 4 7 2
2 5 8 3
3 6 9 4
 
I forgot awk is lazy about keeping its arrays in order... try this:

Code:
awk '
    /[a-z]/{row=0;next}
    {a[row++]=a[row] $1 OFS }
    row > maxrow {maxrow=row}
    END{for (row=0; row<maxrow; row++) {print a[row]}}
' inputfile

Annihilannic.
 
It works a treat!
Thanks Annihilannic
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top