들여쓰기된 출력에서 ​​줄 추출

들여쓰기된 출력에서 ​​줄 추출

쉘 명령에서 ddcutil의 다음 출력을 구문 분석하고 싶습니다.

Model: MQ780
MCCS version: 2.1
Commands:
   Op Code: 01 (VCP Request)
   Op Code: 02 (VCP Response)
   Op Code: 03 (VCP Set)
   Op Code: 0C (Save Settings)
   Op Code: E3 (Capabilities Reply)
   Op Code: F3 (Capabilities Request)
VCP Features:
   Feature: 02 (New control value)
   Feature: 04 (Restore factory defaults)
   Feature: 05 (Restore factory brightness/contrast defaults)
   Feature: 08 (Restore color defaults)
   Feature: 10 (Brightness)
   Feature: 12 (Contrast)
   Feature: 14 (Select color preset)
      Values:
         05: 6500 K
         08: 9300 K
         0b: User 1
   Feature: 16 (Video gain: Red)
   Feature: 18 (Video gain: Green)
   Feature: 1A (Video gain: Blue)
   Feature: 52 (Active control)
   Feature: 60 (Input Source)
      Values:
         11: HDMI-1
         12: HDMI-2
         0f: DisplayPort-1
         10: DisplayPort-2
   Feature: AC (Horizontal frequency)
   Feature: AE (Vertical frequency)
   Feature: B2 (Flat panel sub-pixel layout)
   Feature: B6 (Display technology type)
   Feature: C0 (Display usage time)
   Feature: C6 (Application enable key)
   Feature: C8 (Display controller type)
   Feature: C9 (Display firmware level)
   Feature: D6 (Power mode)
      Values:
         01: DPM: On,  DPMS: Off
         04: DPM: Off, DPMS: Off

다른 스크립트로 파이프할 수 있도록 "Feature:60" 값을 추출하려고 합니다.

11: HDMI-1
12: HDMI-2
0f: DisplayPort-1
10: DisplayPort-2

이를 수행하는 우아한 방법이 있습니까? 나는 다음 정규식을 생각해 냈지만 더 나은 방법이 있을 것이라고 생각했습니다.

$ sudo ddcutil capabilities | pcregrep -M -o2 "(?s)(Feature: 60.*?Values:)(.*?)(Feature)"

출력이 json 형식이고 yaml jq이 있다고 생각 yq하지만 이를 yaml로 허용할 수 없는 경우 사용할 수 있습니다.

답변1

#!/bin/perl
while(<>) {
   if (/Feature: 60/) {
     while(<>) {
       last if (/Feature/);
       next if (/Values/);
       print $_, "\n";
     }
   }
}

단순한:)

답변2

awk를 사용하십시오( 대신 답변을 보여주기 cat file위해 ):sudo ddcutil capabilities

$ cat file |
  awk '$1=="Feature:"{f=($2 == "60"); next} $1=="Values:"{next} f{$1=$1; print}'
11: HDMI-1
12: HDMI-2
0f: DisplayPort-1
10: DisplayPort-2

귀하의 입력 내용에 유사한 상황이 있고 우리가 유사한 부분 비교를 사용하는 경우 $2 == "60"잘못된 일치를 피하기 위해 전체 문자열 비교를 사용하십시오.Feature: 607/Feature: 60/

답변3

사용sed

$ sudo ddcutil capabilities | sed -En '/Feature: 60/{n;/Values:/{:a;n;/Feature:/,/Feature:/!s/^[ \t]+//gp;ba}}'
11: HDMI-1
12: HDMI-2
0f: DisplayPort-1
10: DisplayPort-2

답변4

사용 awk:

sudo ddcutil capabilities | awk '
    /Feature: 60/{ f=1; next }
    f { if (NF==2) print $1, $2; else if ($1=="Feature:") exit }'

관련 정보