【问题标题】:How to convert awk match to powershell command?如何将 awk 匹配转换为 powershell 命令?
【发布时间】:2022-01-20 13:45:03
【问题描述】:

我目前正在一台 linux 机器上运行这个命令来获取超过 1 天的 pod:

kubectl get pod | awk 'match($5,/[0-9]+d/) {print $1}'

我希望能够在 Powershell 中运行相同的命令。我该怎么办?

kubectl get pod 输出:

        NAME       READY     STATUS      RESTARTS      AGE
        pod-name   1/1       Running     0             2h3m
        pod-name2  1/1       Running     0             1d2h
        pod-name3  1/1       Running     0             4d4h

kubectl get pod | awk 'match($5,/[0-9]+d/) {print $1}' 输出:

    pod-name2
    pod-name3

【问题讨论】:

  • kubectl get pod 的输出是什么?
  • @Paolo 我用输出更新了我的原始帖子。请注意,它们可能是类似于 pod-name 的多行
  • 缺少 Awk 脚本的结束引号,并且美元符号前的反斜杠错误。该脚本可以简洁地重写为 $5 ~ /[0-9]+d/
  • @tripleee 刚刚更新。

标签: powershell awk kubectl


【解决方案1】:

在这种情况下,Awk 可能会更方便一些。您必须防止 $split 数组在 where-object 之前在管道中旋转出来。事实证明我仍然可以在 foreach-object 中引用 $split 变量。

'        NAME       READY     STATUS      RESTARTS      AGE
         pod-name   1/1       Running     0             2h3m
         pod-name2  1/1       Running     0             1d2h
         pod-name3  1/1       Running     0             4d4h' | set-content file

get-content file | 
  where-object { $split = -split $_; $split[4] -match '[0-9]+d' } |
  foreach-object { $split[0] }

pod-name2
pod-name3

【讨论】:

    【解决方案2】:

    你可以使用:

    $long_running_pods=(kubectl get pod | Tail -n+2 | ConvertFrom-String -PropertyNames NAME, READY, STATUS, RESTARTS, AGE | Where-Object {$_.AGE -match "[1-9][0-9]*d[0-9]{1,2}h"})
    $long_running_pods.NAME
    

    这将为您提供所有已运行超过一天的 pod。


    例子:

    $long_running_pods=(echo 'NAME       READY     STATUS      RESTARTS      AGE
    pod-name   1/1       Running     0             1d2h
    pod-name2  1/1       Running     0             0d0h' | Tail -n+2 | ConvertFrom-String -PropertyNames NAME, READY, STATUS, RESTARTS, AGE | Where-Object {$_.AGE -match "[1-9][0-9]*d[0-9]{1,2}h"})
    $long_running_pods.NAME 
    

    将打印:

    pod-name
    

    【讨论】:

    • 获取:Tail:术语“Tail”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称
    • @Oplop98 你用的是哪个powershell版本?
    • 我用的是5.1版
    • 你可以用select-object -skip 1代替尾巴。
    • @js2010 Tail 或您发送的内容到底是做什么的?没有它,脚本似乎也能工作
    猜你喜欢
    • 2011-03-07
    • 1970-01-01
    • 2010-10-22
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多