我正在使用aplay -L
它列出多个设备及其描述。
$ aplay -L
null
Discard all samples (playback) or generate zero samples (capture)
pulse
PulseAudio Sound Server
surround40:CARD=PCH,DEV=0
HDA Intel PCH, ALC1220 Analog
4.0 Surround output to Front and Rear speakers
hw:CARD=PCH,DEV=0
HDA Intel PCH, ALC1220 Analog
Direct hardware device without any conversions
其中null
, hw:CARD=PCH,DEV=0
,surround40:CARD=PCH,DEV=0
是设备名称。我想通过设备名称及其描述搜索模式,并找到与其描述匹配的设备名称。
我的期望是
aplay -L | pattern_match_command "Surround output"
surround40:CARD=PCH,DEV=0
类似地会返回
aplay -L | pattern_match_command "pulse"
将返回pulse
。
基本上每个设备的上下文是
surround40:CARD=PCH,DEV=0
HDA Intel PCH, ALC1220 Analog
4.0 Surround output to Front and Rear speakers
目前我正在使用不包含描述的行处理。
aplay -L | grep "pulse"
任何提示我可以使用什么工具。我在用ubuntu 18.04
答案1
使用awk
:
aplay -L |
pat='surround' awk '
BEGIN { pat = tolower(ENVIRON["pat"]) }
/^[^[:blank:]]/ { dev = $0; next }
tolower($0) ~ pat { print dev }'
该awk
命令将记住变量中以非空白字符开头的每一行dev
。每当其他行与给定模式匹配时,dev
就会输出变量的值。
该模式通过环境变量 传入pat
。它被转换为小写并存储在awk
变量中pat
。当模式与行匹配时,该行也会转换为小写,因此在这种意义上模式匹配不区分大小写。
根据您的示例数据,上述命令的输出将是
surround40:CARD=PCH,DEV=0
由于匹配surround
该行中的单词
4.0 Surround output to Front and Rear speakers
答案2
使用具有 PCRE 支持的 GNU grep
mygrep() {
## helper variables to make writing of regex tractable:-
## any nonwhitespace char which is not a colon
noncolon='(?:(?!:)\S)'
nonequal='(?:(?!=)\S)'
# these occur in the description line after the colon, akin to key=value pairs
pair="${nonequal}+=${nonequal}+"
# a header line comprises a run of noncolon nonwhitespace optionally followed by pairs
hdr="${noncolon}+(?::(?:,?${pair})+)?"
# description line is one that begins with a space and has atleast one nonwhitespace
descline='(?:\s.*\S.*\n)'
# supply your string to search for in the description section here ( case insensitive)
srch=$1
t=$(mktemp)
aplay -L | tee "$t" \
| grep -Pzo \
"(?im)^${hdr}\n(?=${descline}*\h.*\Q${srch}\E)" \
| tr -d '\0' \
| grep . ||
grep -iF -- "$1" "$t"
}
## now invoke mygrep with the search string
mygrep 'card=pch'
输出:-
surround40:CARD=PCH,DEV=0
hw:CARD=PCH,DEV=0