while read 循环和变量

while read 循环和变量

我正在寻求你的理事会..因为我碰壁了..在bash脚本中

我想将给定文件的所有行读取到数组中,并运行一组语句来确定所述参数是 true 还是 false 。

下面是示例文件 id,喜欢从每行以数组形式提取值:

2019-11-07 10:07:08,000 p=28290 u=root |  ansclient2                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
2019-11-07 12:48:42,438 p=1830 u=root |  ansclient                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

所以,我正在尝试-

while read -r row ; do
    args=${row[@]}
    #pid
    pc=${row[2]}
    #hostname
    hn=${row[5]}
    #failed row
    st=${row[10]}
    echo $pc
    echo $hn
    echo $st
    if [ $st -eq "failed=0" ] ; then echo "true" 
    else
        echo "failed is something other than 0"
        echo $hn $st
    fi

它没有按预期工作..我希望以数组的形式循环遍历每一行,[while true];并比较'failed='的值以确定其是否为0或其他值。

如果有人可以提供帮助,我将非常感激..

提前致谢

答案1

要读取这样的文件,你最好使用awk

awk '{
    print $3
    print $6
    print $11
    if ($11 == "failed=0") print "true"
    else print "failed is something other than 0"
}' file

答案2

正如@pLumo 所说,awk如果您只想打印出来,这是更好的工具。如果您想使用这些变量做其他奇特的事情并且需要在 bash 脚本中使用它们,那么修改命令read以直接读取数组是正确的选择。

如果您需要整行(变量row)和数组(变量args),您可以这样写:

while IFS= read -r row; do
  read -r -a args <<< "$row"
  # ...
done

默认情况下,IFS设置为所有空格。如果输入是用分号分隔列的 CSV 文件,您可以进行IFS相应的设置:

while IFS= read -r row; do
  IFS=';' read -r -a args <<< "$row"
  # ...
done

答案3

从 pLumo 的回答来看 - 这就是我所选择的 -

#!/bin/bash


#transform the log
grep -i recap -A1 ansible.log |grep -iv recap |grep -v "\-\-" > ansible2.log

#get status of output of said ansible2.log with a success status along with the hostname
#of the job

awk '{print $3, $6, $10, $11
if ($10 == "unreachable=0") print "DEVICE WAS REACHABLE 0"
else if($10 != "unreachable=0") print "DEVICE WAS UNREACHABLE 1"

if ($10 == "unreachable=0")
if ($11 == "failed=0") print "NOTHING FAILED, was successful run"
else print $11 " is something other than 0"
else print $10 " was unreachable" }' ansible2.log

我也想使用 rexkogitansIFS方法,但无法让它正常工作。 。
我试图让 (while)IFS 逐行读取日志,获取要填充的值,这样我就能够迭代它们.. 相反,我的代码会无限循环,或者只是无法正确填充变量: (

我从这段代码中得到了很多输出——[比如 112 行,来自 4 行日志文件.. 不可能是正确的! ]

#!/bin/bash

while IFS='' read -r line 
do 
for i in $line
do
echo "pid is $i ${os[1]} , host is $i ${os[2]}, success is $i ${os[3]}, failed is $i ${os[4]}"
echo "done for that line"
done
done <ans.log

例如,我得到以下输出 -

pid is 2019-11-07  , host is 2019-11-07 , success is 2019-11-07 , failed is 2019-11-07 
done for that line
pid is 10:07:08,000  , host is 10:07:08,000 , success is 10:07:08,000 , failed is 10:07:08,000 
done for that line
pid is p=28290  , host is p=28290 , success is p=28290 , failed is p=28290 
done for that line
pid is u=root  , host is u=root , success is u=root , failed is u=root 
done for that line
pid is |  , host is | , success is | , failed is | 

似乎它未能正确填充变量,而是
每次循环一个变量,而不是正确调用它们..有什么想法吗?

感谢您的所有帮助,抱歉我没有早点回复,需要测试,并通宵工作做系统管理员工作。

谢谢,=-布莱恩

相关内容