【问题标题】:using awk insdie xargs construct使用 awk insdie xargs 构造
【发布时间】:2020-07-11 08:25:04
【问题描述】:

在 xargs 构造中使用 awk:当我想在 xargs 中拉入 awk 时获得不同的输出 - -

第一步

 ~/waste/dgx-users2.log | head -n2
node1
node2

第二步

cat ~/waste/dgx-users2.log | head -n2 | xargs -l1 -- sh -c 'echo $1 && kubectl get pods --field-selector=spec.nodeName=$1,status.phase=Running --all-namespaces --no-headers' --

node1
node2
test-s test-s-pod 3/3   Running   0     6d1h
dummy-s test-s-pod 1/1 Running 0 5d9h

但我只想列出 $1 中的 test-s,因此请在下方过滤

cat ~/waste/dgx-users2.log | head -n2 | xargs -l1 -- sh -c 'echo $1 && kubectl get pods --field-selector=spec.nodeName=$1,status.phase=Running --all-namespaces --no-headers' -- | awk '$1 ~ /test-*/ && /Running/ {print}'
test-s test-pod                       3/3   Running   0     6d

以上都很好,但是有没有办法可以将 awk 拉入 xargs - ?我在下面尝试过,但它缺少在我的预期输出中显示的最后一个输出行。

cat ~/waste/dgx-users2.log | head -n2 | xargs -l1 -- sh -c 'echo $1 && kubectl get pods --field-selector=spec.nodeName=$1,status.phase=Running --all-namespaces --no-headers | awk "$1 ~ /test-*/ && /Running/ {print}"' --
node1
node2

我没有得到相同的输出.. 所以需要调整一些语法,我猜.. 我的预期输出应该是。

我的目标是打印该节点信息以及输出,以便我知道该 pod 在哪个节点上运行,如下面的 node1 没有任何内容,而 node2 有一个 pod。

node1
node2
test-s test-pod                       3/3   Running   0     6d

【问题讨论】:

  • 您能否简化一下,这样我们就不需要您的日志文件来运行它并获得您预期的输出?比如你可以写一个函数gen_log() { cat <<'EOF',有几行log,然后EOF;然后gen_log | xargs -l1 ...
  • 显而易见的问题是,当您从awk '$1 ... 更改为awk "$1... 时,需要更多的转义来阻止$1 在awk 看到它之前被shell 扩展。即把"$1改成"\$1

标签: bash awk xargs


【解决方案1】:

因为 awk 表达式中的 $1 是由 sh 的内部副本在双引号上下文中解析的,所以需要对其进行转义。那就是:

head -n2 <~/waste/dgx-users2.log | xargs -l1 -- sh -c '
    echo "$1" &&
    kubectl get pods --field-selector=spec.nodeName="$1",status.phase=Running \
                     --all-namespaces --no-headers |
    awk "\$1 ~ /test-*/ && /Running/ {print}"
  ' --

【讨论】:

  • 顺便说一句:你认为这样做是对的吗?我的方法有更好的解决方案吗?
  • 我会使用 BashFAQ #1 while read 循环遍历您的文件(或相关子集),而不是使用 xargs。也就是说,如果你走那条路,请注意BashFAQ #24 中描述的问题。
猜你喜欢
  • 2020-12-24
  • 2011-12-26
  • 2014-03-11
  • 1970-01-01
  • 2012-05-22
  • 2014-12-11
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多