首页 > 解决方案 > 在bash中获取匹配行的第一列

问题描述

我从一个 shell 命令得到一个输出,并且想将匹配行的第一列合并到第二个命令中。这是我所拥有的,并且有效:

kubectl get pods -n system | while read string; do


if [[ "$string" == my-pod-* && "$string" == *Running* ]]; then
  #  echo $string
  read -ra ADDR <<< "$string"

  echo
  echo "--- Reading logs for ${ADDR[0]} ---"

  # desired output: kubectl -n system logs my-pod-123 --tail=5 -f
  kubectl -n system logs ${ADDR[0]} --tail=5 -f

fi


done

第一个命令的输出如下所示:

name           status      namespace       running
my-pod-123     Running     system          4h31m      #<<I want this one
another-pod-5  Running     system          5h15m
my-pod-023     Terminating system          8h05m

鉴于输出将仅包含一个匹配项,是否有更短的方法可以做到这一点而无需像这样循环?提前感谢您帮助我提高我的 Bash 技能,因为这看起来很笨拙。

标签: linuxbashstring-matching

解决方案


怎么样grep

wanted=$(kubectl get pods -n system | grep 'my-pod-.*Running')

可以同时做错误检查:

if ! wanted=$(kubectl get pods -n system | grep 'my-pod-.*Running'); then
    echo "Error: no running my-pods" >&2
fi

推荐阅读