ファイルから読み取った2つの数値の比較

ファイルから読み取った2つの数値の比較

9番目の単語が数字の標準形式ファイルを読み取るスクリプトがあります。ファイルから読み取った数字を比較しようとしています。私はその行を正確に読み取ることができ、私が望む方法で正確に動作します。しかし、エラーメッセージが表示されます。

./age.sh: line 8: [: age: integer expression expected

これは私のスクリプトです。

#!/bin/bash
if [ -f $1 ] ;
then
    while read -r LINE || [[ -n $LINE ]]; do
        name=$( echo $LINE | cut -d " " -f1 -f2)
        ago=$( echo $LINE | cut -d " " -f9)     
        echo "$name ----- $age"
        if [ $ago -gt 30 ] ; then
            echo "You get a discount"
        fi
    done < $1
    else
        echo "No file found"
fi

以下はサンプル入力ファイルです。

#FirstName LastName SuperheroName Powers Weapons City Enemy isOutOfEarth Age
Bruce Wayne Batman Martial_arts No_Guns Gowtham Joker No 31
Clark Kent Superman Extreme_strength None Metropolitan Lex_Luther Yes 32
Oliver Queen Green_arrow Accuracy Bow_and_Arrow Star_city Cupid No 30

ベストアンサー1

あなたが経験している特定のエラーは、スクリプトがファイルヘッダーも処理しているためです。簡単な回避策は、次から始まる行をスキップすることです#

#!/bin/bash
if [ ! -f "$1" ]; then
   echo "No file found"
   exit 1
fi

## Use grep -v to print lines that don't match the pattern given. 
grep -v '^#' "$1" | 
while read -r LINE || [ -n "$LINE" ]; do
   name=$( echo "$LINE" | cut -d " " -f1,2)
   age=$( echo "$LINE" | cut -d " " -f9)
   echo "$name ----- $age"
   if [ "$age" -gt 30 ]; then
      echo "You got a discount"
   fi
done

ただし、他の列に対しても操作を行うことができるので、すべての列を変数として読み込みます。

#!/bin/bash
if [ ! -f "$1" ]; then
   echo "No file found"
   exit 1
fi

## read can take multiple values and splits the input line on whitespace
## automatically. Each field is assigned to one of the variables given.
## If there are more fields than variable names, the remaining fields
## are all assigned to the last variable.
grep -v '^#' "$1" | while read -r first last super powers weapons city enemy isout age; do
   echo "$first $last  ----- $age"
   if [ "$age" -gt 30 ]; then
      echo "You got a discount"
   fi
done

おすすめ記事