简体   繁体   English

Bash-将命令输出管道传递到while循环中

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

I'm writing a Bash script where I need to look through the output of a command and do certain actions based on that output. 我正在编写一个Bash脚本,在其中我需要查看命令的输出并根据该输出执行某些操作。 For clarity, this command will output a few million lines of text and it may take roughly an hour or so to do so. 为了清楚起见,此命令将输出几百万行文本,大约需要一个小时左右才能完成。

Currently, I'm executing the command and piping it into a while loop that reads a line at a time then looks for certain criteria. 当前,我正在执行命令并将其管道传递到while循环中,该循环一次读取一行,然后查找某些条件。 If that criterion exists, then update a .dat file and reprint the screen. 如果存在该条件,则更新.dat文件并重新打印屏幕。 Below is a snippet of the script. 以下是脚本的片段。

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

So here's the problem, the sanity check on the data is showing weird results. 这就是问题所在,对数据的完整性检查显示出奇怪的结果。 It is printing lines that don't contain the grep criteria. 它是不包含grep标准的行。

To make sure that my grep statement is working properly, I grep the log file that contains a record of the text that is output by the command and it outputs only the lines that contain the specified criteria. 为了确保我的grep语句正常工作,我对日志文件进行grep记录,该日志文件包含命令输出的文本记录,并且仅输出包含指定条件的行。

I'm still fairly new to Bash so I'm not sure what's going on. 我对Bash还是很陌生,所以我不确定发生了什么。 Could it be that the command is force feeding the while loop a new $line before it can process the $line that met the grep criteria? 可能是该命令在处理符合grep标准的$ line之前强制在while循环中馈入一个新的$ line吗?

Any ideas would be much appreciated! 任何想法将不胜感激!

How does grep know what line looks like? grep如何知道行的样子?

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

But I cant help feel like you are overcomplicating a lot. 但是我不禁感到您过于复杂了。

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 %";

Run the command, filter only matching lines, and pull the sixth element. 运行命令,仅过滤匹配的行,然后拉出第六个元素。 Then if you need to run an arbitrary code on it, send it to a function (you export to make it visible in subprocesses) via xargs. 然后,如果需要在其上运行任意代码,请通过xargs将其发送到函数(导出以使其在子进程中可见)。

What are you applying the grep on ? 您正在将grep用于什么?

Modify 修改

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

as below 如下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM