You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Ansible的stdout_lines中提取指定的bytes行?

提取cbstats输出中含bytes的行的实现方法

有两种常用方式可以实现需求,具体如下:

方式一:在Ansible中通过过滤器过滤结果

直接在with_items中使用select结合search过滤器,筛选出包含bytes的行:

- name: Execute cbstats command
  command: cbstats db-host:db-port -u User -p Password -b orders all
  register: count

- name: Print lines containing 'bytes'
  debug:
    msg: "{{ item }}"
  with_items: "{{ count.stdout_lines | select('search', 'bytes') | list }}"

说明:

  • select('search', 'bytes'):遍历stdout_lines中的每一行,筛选出包含bytes字符串的元素
  • | list:将筛选后的结果转换为列表,符合with_items的输入要求

如果需要精确匹配以bytes开头的行(避免匹配到包含bytes的其他字段名),可以把search换成match:

with_items: "{{ count.stdout_lines | select('match', '^bytes') | list }}"

方式二:在执行命令时直接过滤结果

通过管道结合grep命令,在远程主机上直接过滤输出,减少传输的数据量:

- name: Execute cbstats and filter lines containing 'bytes'
  command: cbstats db-host:db-port -u User -p Password -b orders all | grep bytes
  register: count

- name: Print filtered lines
  debug:
    msg: "{{ item }}"
  with_items: "{{ count.stdout_lines }}"

说明:

  • 利用shell管道在远程端完成过滤,返回的stdout_lines本身就是只包含bytes相关的行,无需再在Ansible中处理
  • 如果需要更精确的匹配(比如只匹配以bytes开头的行),可以使用grep '^bytes'

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:25:30