gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:41 26 4
gpt4 key购买 nike

我正在编写一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com