Awk to Replace a Field Using If Condition
I Have a Text File with Values Record2 300 in Cname Value2 Record3 30 in Cname Value3 Record4 86400 in Cname Value4 Record5 86400 in Cname Value5 Record6 900...
I have a text file with values
record2 300 IN CNAME Value2
record3 30 IN CNAME Value3
record4 86400 IN CNAME Value4
record5 86400 IN CNAME Value5
record6 900 IN CNAME Value6
record7 1600 IN CNAME Value7
record8 1800 IN CNAME Value8
awk '{ if ($2 > "300") ($2 = 300); print $0}' /tmp/file is giving me the output
record2 300 IN CNAME Value2
record3 30 IN CNAME Value3
record4 300 IN CNAME Value4
record5 300 IN CNAME Value5
record6 300 IN CNAME Value6
record7 1600 IN CNAME Value7
record8 1800 IN CNAME Value8
Why this is not replacing 1800 & 1600 fields even though they are > 300 ? I would like to replace second column based on IF condition, can you please help me to find my mistake?
1 Answer
By enclosing "300" in quotes you have forced a lexical (rather than numeric) comparison. To compare numerically omit the quotes:
awk '{ if ($2 > 300) ($2 = 300); print $0}'
or more idiomatically
awk '$2 > 300 {$2 = 300} 1'