PDA

View Full Version : [SOLVED] help needed in shell scripting: awk csv



lucifer663
3rd September 2011, 06:45 PM
Hi
I am new in shell scripting and need some help.
The problem is, I have a csv file with numerical data n1,n2,n3,n4............ I need to make a shell script which will read the csv file and make a new txt file in which all entries are ordered in the following format:

n1 n2 n3
n4 n5 n6
n7 n8 .
. . .
ie. (3 data in a row seperated by space)

i wrote a script

#!/bin/sh
echo "enter file name"
read csvfile
ru=$(awk < $csvfile -F, '{ print $1 }')
echo $ru
echo $ru >> /home/lucifer/new.txt

which is giving output in a single line:

n1 n2 n3...................

how do i get the output in desired format i.e. 3 entries in a line?
any help will be appreciated

den15
3rd September 2011, 08:02 PM
I haven't done enything with bash for a while, but I suppose you could do something like this (consider this more to be a pseude code :)):


j = 1;
for i in $ru do;
X = "$X $i";
if [ `expr $j % 3` -eq 0 ]
then
echo -e "$X\n" >> /home/lucifer/new.txt
X="";
fi
j ++;
done


edit:

Added X="" after echo. I didn't test code, and I do not intend to do it. It was meant only to show the direction and to point to modulo operator, but it crossed my mind the X variable should be reset after echo, so I added that too.

giulix
3rd September 2011, 10:21 PM
order.awk


BEGIN {n = 0; i = 0}
{
n = 0;
while(n < NF) {
n++;
if(i > 2) {
print x[ 0 ] " " x[ 1 ] " " x[ 2 ];
for(i = 0; i < 3; i++) x[ i ] = "";
i = 0;
}
x[ i ] = $n;
i++;
}
}
END { print x[ 0 ] " " x[ 1 ] " " x[ 2 ]; }

Run with


awk -F, -f order.awk inputfile > outputfile

What it does is basically fill a 3 elements array with fields from the input record; once the array is full prints its contents and reinitializes it.

lucifer663
3rd September 2011, 10:56 PM
thanks guys, both of u. u do rock.
script works sweetly now.

giulix
4th September 2011, 01:18 AM
Please, do not send PMs asking for solutions: This sort of questions belong to the forums. This is a solution with a parametric number of columns

order.awk


BEGIN {n = 0; i = 0; l = 0; if(col == 0) l = 3; else l = col;}
{
n = 0;
while(n < NF) {
n++;
if(i > (l - 1)) {
a = "";
for(i = 0; i < l; i++)
a = a x[ i ] " ";
print a;
for(i = 0; i < l; i++)
x[ i ] = "";
i = 0;
}
x[ i ] = $n;
i++;
}
}
END { a = ""; for(i = 0; i < l; i++) a = a x[ i ] " "; print a; }

Run with


awk -F, -vcol=n -f order.awk inputfile > outputfile

where n is the column number

lucifer663
4th September 2011, 08:00 AM
thanks a lot.