1833875 Members
1962 Online
110063 Solutions
New Discussion

Awk Question

 
Filosofo
Regular Advisor

Awk Question

Hi,
I have make a script where I want print all fields separate from a , .
I don't know hoe mach fields there are.
This is a script

cat try.out |while read line
do
line1=`echo $linea |awk 'BEGIN {OFS=","}
{for(i=1;i<=NF;i++)print $i}'`
echo $line1
done

but when I see the output I don't see , between the fields.

Please help

Filo
Sistem engeneer expert
6 REPLIES 6
Mark Grant
Honored Contributor

Re: Awk Question

Hi,

It would be simpler to use "printf" which prints formatted text as in

printf "%s,",$i

which will print $i followed by a comma
Never preceed any demonstration with anything more predictive than "watch this"
Jean-Luc Oudart
Honored Contributor

Re: Awk Question

or simply : print $i,","
Rgds,
JL
fiat lux
Peter Nikitka
Honored Contributor

Re: Awk Question

Hi,

dont't know exactly what you need, but look at this:
echo 'a b c\nd\te f' |
awk -v ORS=, '{for(i=1;iprintf($NF"\n")}'

gives the following output:
a,b,c
d,e,f

So try
awk -v ORS=, '{for(i=1;iprintf($NF"\n")}' try.out

There is no need for cat and Shell-variables.

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Leif Halvarsson_2
Honored Contributor

Re: Awk Question

Hi,
If I undrrstend you correct the fields is separated with spaces and you want output separated with commas. Why not use tr.
Try:
echo "ddd GGG" |tr " " ","
Kent Ostby
Honored Contributor

Re: Awk Question

Cleanest way is to create a file called try.awk:

{for (idx=1;idx {printf("%s,",$idx)}
printf("%s\n",$NF);
}

Then run it in your script as:

awk -f try.awk < try.out > outputfile

"Well, actually, she is a rocket scientist" -- Steve Martin in "Roxanne"
Peter Nikitka
Honored Contributor

Re: Awk Question

Hi Leif,

consider multiple spaces and TABs seperating fields, or white space at the beginning or at the end of a line ... . 'tr' won't do it, then.

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"