identify error in if statement

让人想犯罪 __ 提交于 2019-12-25 03:44:36

问题


Here is the complete code..

What I'm trying to do is this - >

I'm trying to find the average of the values in the second column of the files . If the file has 2.54 in its name, I want to find averages from files called file_2.54_even.xls and file_2.54_odd.xls . If the fiename does not have 2.54 in its name, then simply find the average of file. For example: file_1.60.xls

#!/bin/bash

for file in pmb_mpi tau xhpl mpi_tile_io fftw ; do

    for f in 2.54 1.60 800 ;do

 if [ ${f}  = "2.54" ]
 then 
     echo ${file}_${f}_even_v1.xls
     awk 'sum+=$2 ;END {print "Average = " , $sum/NR > ${file}_${f}_avrg.xls }' ${file}_${f}_even_v1.xls
     echo ${file}_${f}_odd_v1.xls
     awk 'sum+=$2  ;END {print "Average = " , $sum/NR > ${file}_${f}_avrg.xls }' ${file}_${f}_odd_v1.xls
 else
     echo ${file}_${f}_v1.xls 
     awk 'sum+=$2 ;END {print "Average = " , $sum/NR > ${file}_${f}_avrg.xls }' ${file}_{f}_v1.xls
 fi
     done
done

回答1:


Because your awk command is inside single quotes, the shell variables file and f will not be expanded. That's why you're getting the awk errors.

I would use the following script:

#!/bin/bash

for file in pmb_mpi tau xhpl mpi_tile_io fftw ; do
  for f in 2.54 1.60 800 ; do
    if [[ ${f} = "2.54" ]] ; then
      flist=${file}_${f}_even_v1.xls ${file}_${f}_odd_v1.xls
    else
      flist=${file}_${f}_v1.xls
    fi
    cat ${flist} | awk '
      s+=$2;
      END {print "Average = ",$s/NR}
      ' >${file}_${f}_avrg.xls
    # Or use awk '...' ${flist} >${file}_${f}_avrg.xls
    # if you're overly concerned about efficiency of processes.
  done
done

That will simply set flist to either both files or one file, depending on whether f is 2.54 or not, then push that list of files through a single awk script.




回答2:


I believe the problem may be you're comparing integers and strings.

Try

if [ $(f) -eq 2.54 ]

Although not seeing the full code I can't see what line the error is on.

Edit: Trying it in cygwin I get no error however.




回答3:


Can't you just move the redirection?

 awk 'sum+=$2 ;END {print "Average = " , sum/NR }' ${file}_${f}_even_v1.xls > ${file}_${f}_avrg.xls


来源:https://stackoverflow.com/questions/1823166/identify-error-in-if-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!