Grep Shell脚本中仅一行中的字符串

时间:2019-06-06 07:15:42

标签: bash shell

我写了一个shell脚本。 该行将如下所示:

"holderIdentity":"leader-elector1-5cd5b9d76d-ztfgf","numberofLeader":{"":0,"node2":1,"node3":2,"node4":2}"

字符5cd5b9d76d-ztfgf将被随机创建,因此我对grep的关键字仅为leader-elector。而且字符串,"numberofLeader":{"":0,"node2":1,"node3":2,"node4":2}"也是随机的(每次都不同)

如何仅从行中获取此字符串leader-elector1-5cd5b9d76d-ztfgf

非常感谢您!

1 个答案:

答案 0 :(得分:0)

使用GNU grep

grep -Eo 'leader-elector[^"]*' <<< '"holderIdentity":"leader-elector1-5cd5b9d76d-ztfgf","numberofLeader":{"":0,"node2 ":1,"node3":2,"node4":2}"'

否则具有bash regex功能

var='"holderIdentity":"leader-elector1-5cd5b9d76d-ztfgf","numberofLeader":{"":0,"node2 ":1,"node3":2,"node4":2}"'
re='leader-elector[^"]*'

if [[ $var =~ $re ]] ; then
  declare -p BASH_REMATCH
  echo "${BASH_REMATCH[0]}"
fi