Shell-Script

while 讀取循環

  • January 11, 2018

我有一個像下面這樣的文件

var     3   2014   string
var1    4   2011   string4
var2    6   1999   string2
var3    1   2016   string6

然後我有這個 while read 循環來將其中一列與一個數字進行比較,然後回顯一些東西。然而,它並沒有呼應我想要的片語,而是呼應了別的東西。

while read num
do
if [ "$num" = "0" ]; then
echo "Number is equal to zero"
else
echo "number is not equal to 0"
fi
done < home/dir/file.txt | awk '{print $2}' 

它不是回顯上述內容,而是回顯文件的第二列。

你應該試試

awk '{print $2}' home/dir/file.txt | while read num
do
 if [ "$num" = "0" ]; then
   echo "Number is equal to zero"
 else
   echo "number is not equal to 0"
 fi
done 

對於混合的 awk/bash 解決方案。

正如其他人指出的那樣,awk 重定向稍後發生。

看起來您正試圖將輸出重定向home/dir/file.txt | awk '{print $2}'while循環;

首先我猜應該是正確的路徑/home/dir/file.txt(但這只是一個假設);

second/home/dir/file.txt | awk '{print $2}'不會重定向/home/dir/file.txtto的內容awk,而< /home/dir/file.txt awk '{print $2}'會;

第三,您將命令的輸出重定向為文件,但它是一個字元串,您應該將其重定向為:<<< "$(< /home/dir/file.txt awk '{print $2}')".

此外,或者,您可以將命令的輸出直接通過管道傳遞到while循環:< /home/dir/file.txt awk '{print $2}' | while read num.

while read num
do
   if [ "$num" = "0" ]; then
   echo "Number is equal to zero"
else
   echo "number is not equal to 0"
fi
done <<< "$(< /home/dir/file.txt awk '{print $2}')"

或者

< /home/dir/file.txt awk '{print $2}' | while read num
do
   if [ "$num" = "0" ]; then
   echo "Number is equal to zero"
else
   echo "number is not equal to 0"
fi
done

引用自:https://unix.stackexchange.com/questions/208911