A grep (or sed, or awk) command to select all lines that follow a specific pattern after a specific start line in a file

后端 未结 2 1117
甜味超标
甜味超标 2020-12-22 13:48

In the yml files of Docker Compose, the volumes are declared in a section that starts with volumes: line and followed by patterns such

相关标签:
2条回答
  • 2020-12-22 14:09
    awk '$1=="-"{if (f) print; next} {f=/^[[:space:]]*volumes:/}' file
    
    0 讨论(0)
  • 2020-12-22 14:26

    awk one-liner

    Assuming you have / in each volume declaration

    Input :

    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:
    

    Output:

    $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} : 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 : 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
    

    This will reset a if first field isn't -

    0 讨论(0)
提交回复
热议问题