一个 grep(或 sed 或 awk)命令,用于选择文件中特定起始行之后遵循特定模式的所有行 [英] A grep (or sed, or awk) command to select all lines that follow a specific pattern after a specific start line in a file

查看:25
本文介绍了一个 grep(或 sed 或 awk)命令,用于选择文件中特定起始行之后遵循特定模式的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Docker Composeyml 文件中,卷在以 volumes: 行开头的部分中声明,后跟模式,例如作为 -host/dir:guest:dir.该部分以下一部分的开头结束,其名称不会一直相同,并且可以是 ports:environment:网络:,等等.通常有多个 volumes: 部分,并且每个部分中的行数未知(并且在 volumes: 部分中不是恒定的).

In the yml files of Docker Compose, the volumes are declared in a section that starts with volumes: line and followed by patterns such as - host/dir:guest:dir. The sesction ends with the start of the next section, which its name would not be the same all the time, and it could be any of ports:, environment:, and networks:, among others. There is usually more than one volumes: section, and the number of lines in each of those is not known (and is not constant across the volumes: sections).

我需要从 yml 的所有 volumes: 部分中提取所有的 volume 声明(即 -host/dir:guest:dir)代码>文件.

I need to extract all the volume declarations (i.e., - host/dir:guest:dir) from all volumes: sections of a yml file.

谢谢!

示例 yml 文件:

version: '2'
services:
  service1:
    image: repo1/image1
    volumes:
      - /dir1/dir2:/dir3/dir4
      - /dir5/dir6:/dir7/dir8
    ports:
      - "80:80"
  service2:
    image: repo2/image2
    volumes:
      - /dir9/dir10:/dir11/dir12
    environment:
      - A: B

推荐答案

awk one-liner

假设您在每个卷声明中都有 /

Assuming you have / in each volume declaration

输入:

version: '2'
services:
  service1:
    image: repo1/image1
    volumes:
      - /dir1/dir2:/dir3/dir4
      - /dir5/dir6:/dir7/dir8
    ports:
      - "80:80"
  service2:
    image: repo2/image2
    volumes:
      - /dir9/dir10:/dir11/dir12
    environment:
      - A: B
    volumes:
      - /dir1/dir2:/dir3/dir4
      - /dir5/dir6:/dir7/dir8
meow:

输出:

$awk '$0!~"/"{a=0}  /volumes:/{a=1; next}a' file
      - /dir1/dir2:/dir3/dir4
      - /dir5/dir6:/dir7/dir8
      - /dir9/dir10:/dir11/dir12
      - /dir1/dir2:/dir3/dir4
      - /dir5/dir6:/dir7/dir8

$0!~"/"{a=0} :如果记录/行不包含 / 这意味着它不是卷声明;设置 a=0
<代码>/volumes:/{a=1;next} :如果该行包含 volumes: 然后设置 a=1next 即跳转到下一条记录
a : 如果 a=1

$0!~"/"{a=0} : If the record/line doesn't contain / that means it's not a volume declaration ; set a=0
/volumes:/{a=1; next} : If the line contains volumes: then set a=1 and next i.e jump to next record
a : To print the records if a=1

PS :如果在您的 yml 文件中,包含 / 的标签可以紧跟在卷之后,那么这可能会失败.如果是这种情况,请使用此 awk :

PS : If in your yml file a tag containing / can come just after volumes then this can fail. If that's the case then use this awk :

$awk '$1!~"-"{a=0}  /volumes:/{a=1; next}a' file

如果第一个字段不是 -

这篇关于一个 grep(或 sed 或 awk)命令,用于选择文件中特定起始行之后遵循特定模式的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆