You are not logged in.
11:50:37.302 I AlertAppli oid 178371182, priceChange 300, percentChange 4, elapsedTime 1000
need to get the price and percent and check if price > 5000 and percent > 5
#!/bin/gawk -f
BEGIN {
pxChange=length("priceChange")+2;
pcntChange=length("percentChange")+2;
}
{
idx=index($0, "priceChange");
priceChange=substr($0,idx);
price=substr(priceChange,pxChange,index(priceChange,",")-pxChange);
if( price > 5000 ) {
idx=index($0, "percentChange");
percentChange=substr($0,idx);
percent=substr(percentChange,pcntChange,index(percentChange,",")-pcntChange);
if ( percent > 5 ) {
print price"-"percent;
}
}
}
The above script is printing price and percent even when the price is not > 5000 and pcnt is not > 5. What is wrong with the script above?
bash-2.05b$ grep 'priceChange.*percentChange' a_olpa.log | awk -f /var/tmp/a_olpa.awk
600-50
Last edited by srikanthradix (2011-12-12 16:10:33)
This profile is scheduled for deletion.
Offline
Moving to Programming & Scripting.
To know or not to know ...
... the questions remain forever.
Offline
I didn't really look at your code. Also this might be too brittle:
awk -F',| ' -v v=priceChange.*percentChange '$0 ~ v $8>=5000 && $11>=5'
Last edited by steve___ (2011-12-09 19:53:54)
Offline
In Appendix A of the awk book it says: "Each variable and field can potentially be a string or a number or both at any time." The type of a variable is set to the type of the expression you assign to the variable. Fields are special. If the field contains only digits then its type is set to a number. Otherwise, the field is a string. When doing a comparison, if both operands are numbers, then a numeric comparison is performed. If one of the operands is a string then the other is converted to a string before the string comparison is made. A string is "less than" another string if it is earlier in sorted order.
You want a numeric comparison but what you are actually getting is a string comparison. substr is a string function and so returns a string. Coerce the expression into a number by adding zero to it. For example, in an if statement:
if( 0 + price > 5000 ) {
...
Here's a simple way to handle named fields that come in random order... assuming your data is as simple as your example line.
{ price = fld("priceChange"); perc = fld("percentChange") }
price > 5000 && perc > 5 { print price "-" perc }
function fld(name)
{
for(i = 4; i <= NF; i += 2) if($i == name) return 0 + $(i+1)
return 0
}
Notice how I coerce a field's value into a number. When converting expressions from a string to a number, awk reads as many digits from the beginning of the string as it can. Once it runs into the comma character it will stop converting the string to a number expression, ignoring the comma.
Offline
Thanks @steve___ .
Thanks @juster. for pointing the string comparison gaffe.
This profile is scheduled for deletion.
Offline