Variable IF statement in awk


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Variable IF statement in awk
# 1  
Old 01-10-2013
Variable IF statement in awk

I have multiple requirements to run data extracts (with the same basic requriement / resulsts) however the parameters of the extracts change with each request. To help make life easier I am writing a script where the parameters for the specific request are set at the start and then used as needed.
HOWEVER I am having problems with the awk portion of the script.

To simplify matters here is test data and script to explain the problem.

data file as follows (test)
Code:
1 a
2 b
3 c
4 d

in this instance I want to output record 3 c

script as follows:
Code:
parm='&& ($2=="c")';
cat test | awk -v parm="$parm" '{if ((1==1) parm) {print $0}}'

this is outputting the entire file and not just the 3rd record
(note: the (1==1) is a failsafe incase there is no parameter passed)

Last edited by Franklin52; 01-10-2013 at 08:37 AM.. Reason: Please use code tags for data and code samples
# 2  
Old 01-10-2013
Why you need a fail-safe? How about:
Code:
parm="c"

awk -v p=$parm '{
 if(p=="") { print $0; }        # If p is not defined print all records in file.
 else { if($2==p) print $0 }    # If p is defined, then print only that specific record.
}' file

Also note that the cat command is useless, awk is capable of reading the file by itself.
# 3  
Old 01-10-2013
hi bipinajith
my problem is that the filter field changes with each request. next time it could be column 1 or column 10. I need the whole statement to be flexible.
# 4  
Old 01-10-2013
Ok, then how about using a variable for column:-
Code:
col=2
parm="c"

awk -v c=$col -v p=$parm '{if(c=="") { print $0; }else { if($c==p) print $0 }}' file

# 5  
Old 01-10-2013
Quote:
Originally Posted by bipinajith
Why you need a fail-safe? How about:
[CODE]parm="c"

awk -v p=$parm ...
[...]
As a side note:
- in most cases it's safer to quote $param:, just in case the value of $param contains spaces or other shell special characters
and shell word/field splitting is enabled (default for most shells, excluding zsh):

Code:
$ param='a b'
$ # this one fails
$ awk -v p=$param 1 < /dev/null
awk: cmd. line:1: fatal: cannot open file `1' for reading (No such file or directory)
$ # this one succeeds 
$ awk -v p="$param" 1 < /dev/null
$

This User Gave Thanks to radoulov For This Post:
# 6  
Old 01-10-2013
Actually, this could work. awk uses the first parameter - after all option have been evaluated - as the program if nothing else ist supplied with e.g. the -f or -e option:
Code:
$ parm="NR>1 && \$2==\"c\""
$ echo $parm
NR>1 && $2=="c"
$ awk "$parm" file
3 c

Not sure though if it makes sense to supply variables like this...
This User Gave Thanks to RudiC For This Post:
# 7  
Old 01-11-2013
Thank you bipinajith - while that does work I think I may have oversimplified my problem. This awk statement is only one statement in a very complex script, and my parameters are not as simple as $2=c. In one case it may be ($2=='c' || $2==a) && $3=='y'... in another case it may be a completely different set of fields.

My question basically was can you pass full portions of if statment (including all syntax) to awk?? if not I will just have to change the script each time.

RudiC - that may work... thanks will play around with it and see where I get Smilie

---------- Post updated at 01:46 AM ---------- Previous update was at 01:04 AM ----------

Quote:
Originally Posted by RudiC
Actually, this could work. awk uses the first parameter - after all option have been evaluated - as the program if nothing else ist supplied with e.g. the -f or -e option:
Code:
$ parm="NR>1 && \$2==\"c\""
$ echo $parm
NR>1 && $2=="c"
$ awk "$parm" file
3 c

Not sure though if it makes sense to supply variables like this...
THANKS Rudi this works beautifully....

Code:
parm1=" && (\$2==\"c\" || \$2==\"a\")";
parm2="";
echo "$parm1";
echo "$parm2";
cat test | awk '{if ((1==1)'"$parm1""$parm2"') {print $0}}'

results:
Code:
 && ($2=="c" || $2=="a")
1       a
3       c

the reason I am keeping the cat is becuase I am doing various sorts and joins etc with the data prior to the awk statement.
The 1==1 means I don't have to check for the parm1 and parm2 variables being blank. even if they are blank the statement still works (will output all rows).
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Convert Update statement into Insert statement in UNIX using awk, sed....

Hi folks, I have a scenario to convert the update statements into insert statements using shell script (awk, sed...) or in database using regex. I have a bunch of update statements with all columns in a file which I need to convert into insert statements. UPDATE TABLE_A SET COL1=1 WHERE... (0 Replies)
Discussion started by: dev123
0 Replies

2. Shell Programming and Scripting

Variable on If Statement

Hi, I am tasked to modify soem script and I come accross a line which I dont fully understand. I tried searching online but I couldnt get a good explanation on it. Here it the part of the code: PAY_RT=`cat $TEMPFILE | cut -f2 -d","` if ; then PAY_RT=R fi What is... (3 Replies)
Discussion started by: The One
3 Replies

3. Shell Programming and Scripting

if then else; no variable match but statement executes anyway.

My first then statement is executing even though there is no match between the variables. each subsequent if then statement is also executing. Why do they execute when there is no match in the dates? yr=`date +%y` date1=12-31-$yr date=`date +%m-%d-%y` set -vx if ; ... (6 Replies)
Discussion started by: bash_in_my_head
6 Replies

4. Shell Programming and Scripting

awk - updating variable in if statement

I have another question I am stuck at :wall: I have a text file with two columns, like so... 2 0.0627279 3 0.0794451 4 0.108705 5 0.137739 6 0.190394 7 0.217407 8 0.241764 9 0.344458 10 0.460762 I'd like to go through the file line by line until the value in the second column... (3 Replies)
Discussion started by: origamisven
3 Replies

5. Shell Programming and Scripting

Variable is not evaluated in awk statement

Dear All, I have one problem in my script, awk statement as 1. it is not evaluate the second variable $stake but the first one $channel is being done. 2.I want to assign the whole awk statement to a variable actual_code which is not being executed in my script. #!/usr/bin/sh echo "Enter... (3 Replies)
Discussion started by: chinmayadalai
3 Replies

6. Shell Programming and Scripting

Select variable within a if statement

i want to select a variable created and use it in a if statement, but not getting the desired results LINE='device for 0101a01: lpd://172.25.41.111:515' prt=`echo $LINE | awk '{print $3 }' | cut -c 1-7` echo $prt My if statement to select just what i want.. IFS=$":" while read prt... (11 Replies)
Discussion started by: ggoliath
11 Replies

7. Shell Programming and Scripting

Assigning Variable to AWK statement

Hi, The following command runs on in the Korn shell prompt. however i want to output the value of this to a variable. Can anyone provide a solution? echo 'ABC,DEF,"G,HI,J",KLM,"MNi,O"'| awk -F "\"" '{for(i=1;i<=NF;i++){if(i%2)gsub("\,","~^~",$i)}}1' (2 Replies)
Discussion started by: ladarlsan
2 Replies

8. Shell Programming and Scripting

If statement in awk with external variable

So I have a if statement inside an awk to check if $2 of a awk equals a specific IP but the test fails. So here is what I have. # !/bin/sh echo "Enter client ID" read ID echo "Enter month (01, 02, 03)" read month echo "Enter day (03, 15)" read day echo "Enter Year (07, 08)" read... (6 Replies)
Discussion started by: doublejz
6 Replies

9. Shell Programming and Scripting

Can't interpret variable in if statement

Can someone help me out here. I can't get this piece of code to work. i.e. $ALL_EVENTS does not get interpreted in the if brackets. The first part is the code, the second part is the execution of the code. Note: $ALL_EVENTS does equal 2, but there is no value once passed to the if statement. ... (4 Replies)
Discussion started by: jwholey
4 Replies

10. Shell Programming and Scripting

Using variable in case statement

I want to do this: Ex 1: case $answer in 1|2|3|4|5) echo $answer;; x) break;; *) echo "Invalid selection. Try again.";; esac But I need the part "1|2|3|4|5" to be fetched from a variable, like so: Ex 2: case $answer in $cases) echo $answer;; x) break;; *) echo "Invalid... (2 Replies)
Discussion started by: fialia
2 Replies
Login or Register to Ask a Question