while ループと if ステートメントは、条件が満たされると異なるコマンドを実行します。

while ループと if ステートメントは、条件が満たされると異なるコマンドを実行します。

~へfile.txt

chicken sheep cow  
tomato cucumber  
banana

if声明なし

while read -r column1 column2 column3; do  
    command  
done < file.txt

ステートメントを使用すると、if行に3つの列がある場合は何を行います。2つの列がcommand1ある場合はcommand2どうすればよいですかcommand3

ベストアンサー1

または他の方法あなたの例と最小の違いは次のとおりです。

#!/bin/bash

while read -r column1 column2 column3; do
        if [ -z "$column2" ] ; then
                printf '%s\n' "Only first column has data"
        elif [ -z "$column3" ]; then
                printf '%s\n' "Only first and second columns has data"
        elif [ -n "$column3" ]; then
                printf '%s\n' "All three columns has data"
        fi
done < file.txt

出力は次のとおりです。

All three columns has data
Only first and second columns has data
Only first column has data

ノート:

あなたの例では、1行目と2行目の末尾に複数のスペースが含まれていますが、readすべての前後のスペース文字はデフォルトで削除されます。

入力に3つ以上の列が含まれている場合、3番目以降の列のすべてのデータはcolumn3

バラよりファイル(データストリーム、変数)を1行ずつ(および/またはフィールドごとに)読み取る方法は?

おすすめ記事