1755466 Members
4390 Online
108833 Solutions
New Discussion юеВ

Awk help

 
SOLVED
Go to solution
cbres00
Frequent Advisor

Awk help

I need to redirect awk output depending on how many pipes I find in a file. Logic would go like this:

awk 'BEGIN { FS="|"; OFS="|" }
{ (if NF = 4 )
{ print $0 } > good_file.txt
else
{ print $0 } > bad_file.txt
} < input_file.txt

I keep getting the cryptic awk "something wrong on line 3" message. What am I missing here?

Regards,
CB




Life is too short not to have fun every single day
16 REPLIES 16
A. Clay Stephenson
Acclaimed Contributor

Re: Awk help

The first thing that jumps out at me is
if (NF = 4)
I assume you meant a comparison rather than an assignment. Use "==".
If it ain't broke, I can fix that.
cbres00
Frequent Advisor

Re: Awk help

Yes. I still get an error msg on line 3, however.
Life is too short not to have fun every single day
A. Clay Stephenson
Acclaimed Contributor

Re: Awk help

Okay, I see a beginning single-quote but no terminal single-quote.
If it ain't broke, I can fix that.
cbres00
Frequent Advisor

Re: Awk help

Sorry....i have that in there, too. ;-)

Is my syntax correct for the 'if' statement?
I've tried restructuring this several ways but still no success. Obviously I haven't hit the right way.

CB
Life is too short not to have fun every single day
Hein van den Heuvel
Honored Contributor

Re: Awk help

man awk...
print [expression-list] [ > expression]

So you need to (double)quote file.txt to make it an expression. And you have the closing curly brace in the wrong place.
Try something like:


awk '{ if (NF==2) {print $0 >> "good_file.txt"} else {print $0 >> "bad_file.txt"}}'
aap
aap noot
aap noot mies
$ cat good_file.txt
aap noot
$ cat bad_file.txt
aap
aap noot mies

Hein.

A. Clay Stephenson
Acclaimed Contributor

Re: Awk help

Okay, I see a beginning single-quote but no terminal single-quote.

Next (if NF = 4) should be "if (NF == 4)".
No quotes around the filename:

awk 'BEGIN { FS="|"; OFS="|" }
{
if (NF == 4 ) print $0 > "good_file.txt"
else print $0 > "bad_file.txt"
}' < input_file.txt

should be close.
If it ain't broke, I can fix that.
H.Merijn Brand (procura
Honored Contributor

Re: Awk help


# perl -aF\\\| -pe'select@F==4?STDOUT:STDERR' input_file.txt >good_file.txt 2>bad_file.txt

or

# perl -aF\\\| -ne'print{@F==4?STDOUT:STDERR}$_' input_file.txt >good_file.txt 2>bad_file.txt

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
cbres00
Frequent Advisor

Re: Awk help

Hmmmm....still not working.
I also need to replace the file name with a variable but I'm not sure it would matter.

cb
Life is too short not to have fun every single day
A. Clay Stephenson
Acclaimed Contributor

Re: Awk help

Well, I just cut and pasted my last example and it worked. I won't suggest that your method are optimal but there should be no syntax errors.
If it ain't broke, I can fix that.