Home > Software design >  Convert str to int in shell(bash/zsh)
Convert str to int in shell(bash/zsh)

Time:02-22

I have a .txt file which is similar to a dataframe. It looks like this

1 VJj9TG 22fH93 outcome exposure MR_Egger 229 -0.154541387533697 0.183937771386433 0.401689844329968
2 VJj9TG 22fH93 outcome exposure Weighted_median 229 -0.427118364148873 0.0902880245931322 2.23834809459446e-06
3 VJj9TG 22fH93 outcome exposure Inverse_variance_weighted 229 -0.276133832468094 0.0519157920241822 1.04408357721305e-07
4 VJj9TG 22fH93 outcome exposure Simple_mode 229 -0.582591827578286 0.399305210006009 0.145937580996065

If the values of the last column of row 2 and row 3 are both less than 0.05, then I want to move this .txt file to another directory. So my shell script goes like this

a1=$(awk 'NR==2{print $NF}' $1/$file)
a2=$(awk 'NR==3{print $NF}' $1/$file)
if [ $a1 -le 0.05 ] && [ $a2 -le 0.05 ]; then
mv $1/$file $2/$file
fi

The problem is: a1 a2 seem to be of type string instead of integer or float, and the error reads as:

[: integer expression expected: 2.23834809459446e-06

So I was wondering how I could convert a1 to an integer and compare it to 0.05.

CodePudding user response:

Check your conditions within awk and exit accordingly:

if awk 'NR==2 && $NF>0.05 {exit 1} NR==3 {exit $NF>0.05}' $1/$file
then
  mv $1/$file $2/$file
fi

CodePudding user response:

-le compares integers.

But you tagged your question for bash and zsh. In zsh, you could do a

if (( a1 <= 0.05 && a2 <= 0.05 )); then

since zsh can do floats.

  • Related