获取 bash 中匹配行的第一列
getting first column of a matching line in 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 技能,因为这看起来很笨拙。
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
您可以这样使用 awk
:
name=$(kubectl get pods -n system | awk '/^my-pod.*Running/{print }')
[[ -n $name ]] && kubectl -n system logs "$name" --tail=5 -f
awk
命令将在一行的开头匹配模式 my-pod.*Running
,如果找到它,那么它将打印第一列。我们将其存储在变量 name
.
中
如果 $name
不为空,则我们使用该值调用 kubectl -n system logs
。
我正在从 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 技能,因为这看起来很笨拙。
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
您可以这样使用 awk
:
name=$(kubectl get pods -n system | awk '/^my-pod.*Running/{print }')
[[ -n $name ]] && kubectl -n system logs "$name" --tail=5 -f
awk
命令将在一行的开头匹配模式 my-pod.*Running
,如果找到它,那么它将打印第一列。我们将其存储在变量 name
.
如果 $name
不为空,则我们使用该值调用 kubectl -n system logs
。