~へ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