1830207 Members
1925 Online
109999 Solutions
New Discussion

Re: AWK

 
SOLVED
Go to solution
Chern Jian Leaw
Regular Advisor

AWK

HI,

I trying to extract the fields in a txt file separated by commas as below:

abc,hhh,lll,kkk,ppp,
dajd,dkjdk,nnn
mmm

I tried using the script below to extract the these fields, place them into an array and write the array contents into a file.

cat test.sh:

BEGIN {
split($0, fieldArray, ",")
for(i in field){
print field[i]
field[i] >> groupfile
}
}

However, it does not produce any results into the groupfile, but produces a parse error at:
field[i] >> groupfile

I tried running the script as follows on the command line:
$awk -f test.sh inputfile

How should I solve this problem ?

Also, what if I were to have 2 different separators in the input file:
wmt:*abc-nn-mm:306:abc,kkk,ppp,...
....,abn

I would only need to extract the fields separated by the commas, not the colons.

How should also do this?

Thanks.
9 REPLIES 9
Heiner E. Lennackers
Respected Contributor
Solution

Re: AWK

Hi,

try this:

awk '{
split($0, field, ",");
for (i in field) {
print field[i] >> groupfile
}
}' input_file

In split you can use a regular expression as seperator. if you want to use * and , as separator, just try:
split ($0, field, "[*,]")

Heiner

if this makes any sense to you, you have a BIG problem
Deepak Extross
Honored Contributor

Re: AWK

You'll find it easier to use the -F option to specify ' as your delimiter. See man awk for details.
Chern Jian Leaw
Regular Advisor

Re: AWK

HI Heiner,

It produced an ^Invalid char '`' in expression.

Is the sign after awk, a ` or ' and the sign after closing statement a ' or `, as either one produces the same error...?

Please advice.


Thanks.
John Carr_2
Honored Contributor

Re: AWK

Hi

try this

cat filename | akw -F"," '{ print $1 $2 $3 }'

cheers
JOhn.
Chern Jian Leaw
Regular Advisor

Re: AWK

HI John,

If the text file has only very little entries, then it works. Unfortunately, the file is rather huge with lots of such entries separated by commas.

Please advice.
Thanks.


Deepak Extross
Honored Contributor

Re: AWK

Chern,
These are single-quotes (the ones above the ? key).

The following works fine for me:
awk '{
split($0, field, ",");
for (i in field) {
print field[i]
}
}' input_file >> ./groupfile
John Carr_2
Honored Contributor

Re: AWK

Chern

can you attach a section of the file so we know what we are dealing with

cheers
John.
Robin Wakefield
Honored Contributor

Re: AWK

Hi,

Try:

awk -F, '{for (i=1;i<=NF;i++){print $i}}' infile > outfile

Rgds, Robin
H.Merijn Brand (procura
Honored Contributor

Re: AWK

l1:/tmp 102 > cat >xx
aa,bb,dvfgrh:nfbe,fgr;hfhr-z
243,9474632 jfkweh,fdfwe
l1:/tmp 103 > perl -naF, -e '$"="\n";print"@F"' xx
aa
bb
dvfgrh:nfbe
fgr;hfhr-z
243
9474632 jfkweh
fdfwe
l1:/tmp 104 >
Enjoy, Have FUN! H.Merijn