我想在 shell 命令中解析下面的输出(来自 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 格式,我可以使用jq
,并且我认为有yq
yaml,但我无法让它接受它作为 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 }'