在 Bash 脚本中解析命令输出

4

我想运行一个命令,它会输出以下内容并进行解析:

[VDB VIEW]
[VDB] vhctest
        [BACKEND] domain.computername: ENABLED:RW:CONSISTENT
        [BACKEND] domain.computername: ENABLED:RW:CONSISTENT
        ...

我只对一些关键词感兴趣,例如“ENABLED”等。我无法仅搜索ENABLED,因为我需要逐行解析每个行。

这是我的第一个脚本,我想知道是否有人可以帮助我?

编辑: 现在我有:

cmdout=`mycommand`

while read -r line
do
   #check for key words in $line
done < $cmdout

我以为这样可以实现我的需求,但它总是在输出命令结果之前输出以下内容:

./myscript.sh: 29: cannot open ... : No such file

我不想写入文件来实现这个目的。

这里是伪代码:

cmdout=`mycommand`

loop each line in $cmdout
   if line contains $1
       if line contains $2
            output 1
       else
            output 0

@Mr Shoubs - 嗯...尝试使用 YOUR_COMMANDS | grep -e "YOUR_KEYWORD1\|YOUR_KEYWORD2\|..." 或将输出导入文件。 - ajreal
我正在搜索的每个关键字都是互斥的 - 例如,我想知道每行包含哪个关键字。这最终将与Nagios一起使用。 - Mr Shoubs
3个回答

5
错误的原因是:
done < $cmdout

认为$cmdout的内容是文件名。

你可以选择以下操作:

done <<< $cmdout

或者

done <<EOF
$cmdout
EOF

或者

done < <(mycommand)    # without using the variable at all

或者

done <<< $(mycommand)

或者

done <<EOF
$(mycommand)
EOF

或者

mycommand | while
...
done

然而,最后一种方法会创建一个子shell,并且在循环中设置的任何变量都将在循环退出时丢失。


0
$ cat test.sh
#!/bin/bash
while read line ; do
if [ `echo $line|grep "$1" | wc -l` != 0 ]; then
    if [ `echo $line|grep "$2" | wc -l` != 0 ]; then
        echo "output 1"
    else
        echo "output 0"
    fi
fi

done

用法

$ cat in.txt | ./test.sh ENABLED  RW
output 1
output 1

这不是最好的解决方案,但它是你想要的逐字翻译,并且应该给你一个开始并添加自己逻辑的东西。


如果 echo "$line" | grep -q "$1" 成立,则执行以下操作。 - Dennis Williamson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接