【问题标题】:getting first column of a matching line in bash在bash中获取匹配行的第一列
【发布时间】:2021-05-05 21:38:01
【问题描述】:

我从一个 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 技能,因为这看起来很笨拙。

【问题讨论】:

    标签: linux bash string-matching


    【解决方案1】:

    你可以像这样使用awk

    name=$(kubectl get pods -n system | awk '/^my-pod.*Running/{print $1}')
    [[ -n $name ]] && kubectl -n system logs "$name" --tail=5 -f
    

    awk 命令将在行首匹配模式my-pod.*Running,如果找到,它将打印第一列。我们将其存储在变量 name 中。

    如果$name 不为空,那么我们使用该值调用kubectl -n system logs

    【讨论】:

    • 这绝对比我的更精简,谢谢!这也有助于我第一次看到awk 的使用。
    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 2013-06-11
      • 1970-01-01
      • 2015-12-01
      • 2018-09-21
      • 2017-11-30
      相关资源
      最近更新 更多