如何解决Bash脚本如何以自定义顺序显示匹配的单词
以下是命令ads2 cls create
kernel with pid 7148 (port 9011) killed
kernel with pid 9360 (port 9011) killed
probing service daemon @ http://fdt-c-vm-0093.fdtech.intern:9010
starting kernel FDT-C-VM-0093 @ http://fdt-c-yy-0093.ssbt.intern:9011 name=FDT-C-VM-0093 max_consec_timeouts=10 clustermode=Standard hostname=FDT-C-VM-0093 framerate=20000 schedmode=Standard rtaddr=fdt-c-vm-0093.fdtech.ssbt tickrole=Local tickmaster=local max_total_timeouts=1000
kernel FDT-C-VM-0093 running
probing service daemon @ http://172.16.xx.xx:9010
starting kernel FDT-C-AGX-0004 @ http://172.16.xx.xx:9011 name=FDT-C-AGX-0004 max_consec_timeouts=10 clustermode=Standard hostname=FDT-C-AGX-0004 framerate=20000 schedmode=Standard rtaddr=172.16.xx.xx tickrole=Local tickmaster=local max_total_timeouts=1000
kernel Fxx-x-xxx-xxx4 running
>>> start cluster establish ...
>>> cluster established ...
nodes {
node {
name = "FDT-C-VM-xxxx";
address = "http://fxx-x-xx-0093.xxx.intern:xxxx/";
state = "3";
}
node {
name = "xxx-x-xxx-xxx";
address = "http://1xx.16.xx.xx:9011/";
state = "3";
}
}
但是,我试图为每个节点提取 name
和 state
的值,将它们保存在一个变量中并按以下顺序显示它们:
**#example output**
Node fdt-c-agx-xxx has state 3
Node FDT-C-VM-xxx has state 3
直到现在,在这个如此强大的学习网站的帮助下,我可以通过执行以下操作来提取 name
和 state
的值:
cls="$(ads2 cls create | grep '\(state\|name\) =' | cut -d '"' -f 2)"
现在,如果我打印 cls
变量,我会得到以下信息:
FDT-C-VM-xxx
3
FDT-C-AGX-xxx
3
第一个问题:
如何在 **#example output**
中显示与上面类似的结果?
第二个问题
使用此实现,我如何检查两个节点的 state
变量的值以打印类似
if node1State = 3 && node2State = 3; then
echo "Sucess"
else
echo "Failed"
解决方法
由于输出似乎是 json,你真的应该使用一个 json 解析器,比如 jq,但在没有 jq 的情况下,你可以使用 awk 并结合问题一和问题二的要求:
ads2 cls create | awk -F [\"] '/^>>> cluster established .../ { strt=1 } strt!=1 { next } $1 ~ "name" { cnt++;nam[cnt]=$2 } $1 ~ "state" { stat[cnt]=$2;print "Node "nam[cnt]" has state "$2 } END { if (stat[1]=="3" && stat[2]=="3") { print "Success" } else { print "Failed" } }'
说明:
ads2 cls create | awk -F [\"] ' # Set the field delimiter to a double quote
/^>>> cluster established .../ {
strt=1 # If the line starts with ">>> cluster established ...",set a variable strt to 1
}
strt!=1 {
next # If strt is not equal to 1,skip to the next line
}
$1 ~ "name" {
cnt++; # If the first field contains name,increment a cnt variable
nam[cnt]=$2 # Use the cnt variable as the index of an array called nam with the second field the value
}
$1 ~ "state" {
stat[cnt]=$2; # When the first field contains "state",set up another array called stat
print "Node "nam[cnt]" has state "$2 # Print the node name as well as the state
}
END {
if (stat[1]=="3" && stat[2]=="3") {
print "Success" # At the end of processing,use the array to determine whether there is a success of failure.
}
else {
print "Failed"
}
}'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。