LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   awk help pls.. a bit complex... (https://www.linuxquestions.org/questions/programming-9/awk-help-pls-a-bit-complex-866531/)

voda87 03-04-2011 10:16 PM

awk help pls.. a bit complex...
 
Hi all, I am using an awk command to print a line from a cvs file.
the awk command includes an if statement that filter the output
-lets say i want to print all the lines that the price field is greater than 30.
i have it working when i put the parameters myself.. but when i try to send them with vars it wont work..
i am sending the sign of the if statement - can only be: == , < , >

it looks like this:
cat file.csv | awk -v sign=">" -v field="2000" '{if($3 sign field) printf "%-12s%-12s%-12s%-12s\n",$1,$2,$3,$4}' FS=\,

the bold part is the problem , because when i put the sign parameter myself t works great.. i guess its a chars issue but i cant spot it..

Thanks, i'll appreciate any idea.. :Pengy:

David the H. 03-05-2011 12:14 AM

First of all, please use [code][/code] tags around your code, to preserve formatting and to improve readability.

It usually also helps to give a sample of the input text, and the exact error messages you get from the commands.

Anyway, I can't say for sure, but after working with it for a bit, it looks to me like awk simply doesn't recognize conditional operators when they're stored in variables. Perhaps it has something to do with the way awk treats variable contents as regexes when used in tests, instead of as simple strings, or something.

After stripping your command above down to the essentials, the only easy way I could find around it was to use creative quoting, so the shell variable can be used directly in the statement.
Code:

sign=">"
test_shell=2000
$ awk -v test=$test_shell '{ if ($3 '"$sign"' test) {print}}' file.csv

Notice how I unquoted the $sign variable (and re-quoted it in double-quotes). This way it will be expanded before the expression is passed to awk. You could do the same thing with the test variable too, of course.

Finally, there's no point in using cat and a pipe when awk can read directly from the file.

voda87 03-06-2011 04:03 PM

TY David, worked perfectly!

David the H. 03-06-2011 11:45 PM

Glad to help. Now please follow the advice in my signature. :)


All times are GMT -5. The time now is 08:21 PM.