linux - Bash - 将命令输出管道化到 while 循环中

标签 linux bash shell while-loop pipe

我正在编写一个 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 还是很陌生,所以我不确定发生了什么。会不会是命令在 while 循环处理满足 grep 条件的 $line 之前强制为其提供新的 $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 将其发送到函数(导出以使其在子进程中可见)。

关于linux - Bash - 将命令输出管道化到 while 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45721734/

相关文章:

linux - 从用户空间读取设备树的 API

linux - 我想添加本地仓库的远程分支?

bash - 如何将多个公钥转换为一行?

linux - 在 bash 中应用 CHMOD 并压缩文件

python - 抑制 Python/unittest 的所有输出

linux - 如何在通过中间服务器连接的本地服务器和远程服务器之间传输数据?

ruby - 在 ruby​​ 的当前终端中运行命令,然后在退出时执行代码

linux - Ubuntu 12.04 升级 boost 1.46 到 1.60

android - 从命令行删除持久僵尸进程

linux - Bash-cat 中隐藏着。文件或写入