簡體   English   中英

Bash-將命令輸出管道傳遞到while循環中

[英]Bash - Piping output of command into while loop

我正在編寫一個Bash腳本,在其中我需要查看命令的輸出並根據該輸出執行某些操作。 為了清楚起見,此命令將輸出幾百萬行文本,大約需要一個小時左右才能完成。

當前,我正在執行命令並將其管道傳遞到while循環中,該循環一次讀取一行,然后查找某些條件。 如果存在該條件,則更新.dat文件並重新打印屏幕。 以下是腳本的片段。

eval "$command"| while read line ; do
    if grep -Fq "Specific :: Criterion"; then
        #pull the sixth word from the line which will have the data I need
        temp=$(echo "$line" | awk '{ printf $6 }')
        #sanity check the data
        echo "\$line = $line"
        echo "\$temp = $temp"

        #then push $temp through a case statement that does what I need it to do.
    fi
done

這就是問題所在,對數據的完整性檢查顯示出奇怪的結果。 它是不包含grep標准的行。

為了確保我的grep語句正常工作,我對日志文件進行grep記錄,該日志文件包含命令輸出的文本記錄,並且僅輸出包含指定條件的行。

我對Bash還是很陌生,所以我不確定發生了什么。 可能是該命令在處理符合grep標准的$ line之前強制在while循環中饋入一個新的$ line嗎?

任何想法將不勝感激!

grep如何知道行的樣子?

if ( printf '%s\n' "$line" | grep -Fq "Specific :: Criterion"); then

但是我不禁感到您過於復雜了。

function process() { 
    echo "I can do anything I want"
    echo " per element $1"
    echo " that I want here"
}

export -f process

$command | grep -F "Specific :: Criterion" | awk '{print $6}' | xargs -I % -n 1 bash -c "process %";

運行命令,僅過濾匹配的行,然后拉出第六個元素。 然后,如果需要在其上運行任意代碼,請通過xargs將其發送到函數(導出以使其在子進程中可見)。

您正在將grep用於什么?

修改

if grep -Fq "Specific :: Criterion"; then

如下

if ( echo $line | grep -Fq "Specific :: Criterion" ); then

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM