Linux 在 Bash 脚本中解析命令输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4276924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing Command Output in Bash Script
提问by Mr Shoubs
I want to run a command that gives the following output and parse it:
我想运行一个提供以下输出的命令并解析它:
[VDB VIEW]
[VDB] vhctest
[BACKEND] domain.computername: ENABLED:RW:CONSISTENT
[BACKEND] domain.computername: ENABLED:RW:CONSISTENT
...
I'm only interested in some key works, such as 'ENABLED' etc. I can't search just for ENABLED as I need to parse each line at a time.
我只对一些关键作品感兴趣,例如“ENABLED”等。我不能只搜索 ENABLED,因为我需要一次解析每一行。
This is my first script, and I want to know if anyone can help me?
这是我的第一个脚本,我想知道是否有人可以帮助我?
EDIT: I now have:
编辑:我现在有:
cmdout=`mycommand`
while read -r line
do
#check for key words in $line
done < $cmdout
I thought this did what I wanted but it always seems to output the following right before the command output.
我认为这做了我想要的,但它似乎总是在命令输出之前输出以下内容。
./myscript.sh: 29: cannot open ... : No such file
./myscript.sh: 29: 无法打开... : 没有这样的文件
I don't want to write to a file to have to achieve this.
我不想写入文件来实现这一点。
Here is the psudo code:
这是伪代码:
cmdout=`mycommand`
loop each line in $cmdout
if line contains
if line contains
output 1
else
output 0
采纳答案by Paused until further notice.
The reason for the error is that
错误的原因是
done < $cmdout
thinks that the contents of $cmdout
is a filename.
认为的内容$cmdout
是一个文件名。
You can either do:
你可以这样做:
done <<< $cmdout
or
或者
done <<EOF
$cmdout
EOF
or
或者
done < <(mycommand) # without using the variable at all
or
或者
done <<< $(mycommand)
or
或者
done <<EOF
$(mycommand)
EOF
or
或者
mycommand | while
...
done
However, the last one creates a subshell and any variables set in the loop will be lost when the loop exits.
但是,最后一个创建了一个子shell,当循环退出时,循环中设置的任何变量都将丢失。
回答by Ignacio Vazquez-Abrams
回答by qwerty
$ cat test.sh
#!/bin/bash
while read line ; do
if [ `echo $line|grep "" | wc -l` != 0 ]; then
if [ `echo $line|grep "" | wc -l` != 0 ]; then
echo "output 1"
else
echo "output 0"
fi
fi
done
USAGE
用法
$ cat in.txt | ./test.sh ENABLED RW
output 1
output 1
This isn't the best solution, but its a word by word translation of what you want and should give you something to start with and add your own logic
这不是最好的解决方案,但它是你想要的逐字翻译,应该给你一些开始并添加你自己的逻辑