MyTetra Share
Делитесь знаниями!
Awk Greater Than Less Than
Время создания: 21.04.2014 14:16
Текстовые метки: awk
Раздел: root - Linux - Console - awk
Запись: Yurons/mytetra/master/base/1398079000f8hhx8qwwm/text.html на

he reason it fails when you use variables is because the awk script enclosed by single quotes is evaluated by awk and not bash: so if you'd like to pass variables you are using from bash to awk, you'll have to specify it with the -v option as follows:



result=$(awk -v n1=$num1 -v n2=$num2 'BEGIN{print (n2>n1)?1:0}')

Note that program variables used inside the awk script must not be prefixed with $

Try doing this :

result=$(awk -v num1=2.2 -v num2=4.5 'BEGIN{print (num2 > num1) ? 1 : 0}')

See :

man awk | less +/'^ *-v'share|improve this answer

Because $num1 and $num2 are not expanded by bash -- you are using single quotes. The following will work, though:

result=$(awk "BEGIN{print ($num2>$num1)?1:0}")

Note, however, as pointed out in the comments that this is poor coding style and mixing bash and awk. Personally, I don't mind such constructs; but in general, especially for complex things and if you don't remember what things will get evaluated by bash when in double quotes, turn to the other answers to this question.

See the excellent example from @EdMorton below in the comments.

EDIT: Actually, instead of awk, I would use bc:



result=$( echo "$num2 > $num1" | bc )

Why? Because it is just a bit clearer... and lighter.

Or with Perl (because it is shorter and because I like Perl more than awk and because I like backticks more than $():

result=`perl -e "print ( $num2 > $num1 ) ? 1 : 0;"`

Or, to be fancy (and probably inefficient):

if [ `echo -e "$num1\n$num2" | sort -n | head -1` != "$num1" ] ; then result=0 ; else result=1 ; fi

(Yes, I know)

I had a brief, intensive, 3-year long exposure to awk, in prehistoric times. Nowadays bash is everywhere and can do loads of stuff (I had sh/csh only at that time) so often it can be used instead of awk, while computers are fast enough for Perl to be used in ad hoc command lines instead of awk. Just sayin'.

MyTetra Share v.0.60
Яндекс индекс цитирования