这是一种实现方法awk
(整个输出由答案中的代码完成)。
当最终一次又一次地重新处理相同的输入时,通常表明另一种方法可能更好。
awk
非常适合处理这样的文本输入。awk
程序要比用完成的事情长很多sed
,但是它们更易于阅读,您可以在其中添加打印语句以使调试更加容易。
我把调试语句留了下来(注释掉了)。您可以取消注释他们以观察脚本的工作原理。
您必须将awk
程序放在某个用例中最简单的位置,例如,将整个事情放在awk
命令行中用单引号引起来的字符串中。
这样,您不必将其存储在单独的文件或临时文件中,因此不涉及文件管理,脚本将独立运行。
该程序看起来很长,但是几乎所有注释,调试语句和空白。
#!/bin/bash
## Whole awk program is one single quoted string
## on the awk command line
## so we don't need to put it in a separate file
## and so bash doesn't expand any of it
## Debugging statements were left in, but commented out
/usr/bin/cpuid | awk '
BEGIN { ## initialize variables - probably unnecessary
em = ""
ef = ""
fa = ""
mo = ""
si = ""
ps = ""
}
## get each value only once
## extended model is in field 4 starting at the third character
## of a line which contains "extended model"
/extended model/ && em == "" {
em = substr($4, 3)
##print "EM " em
}
## extended family is in field 4 starting at the third character
## of a line which contains "extended family"
/extended family/ && ef == "" {
ef = substr($4, 3)
##print "EF " ef
}
## family is in the last field, starting at the second character
## and is two characters shorter than the field "()"
## of a line which starts with "family"
## (so it does not match "extended family")
$1 == "family" && fa == "" {
##print NF " [" $NF "]"
##print "[" substr($NF, 2) "]"
l = length($NF) - 2
fa = substr($NF, 2, l)
##print "FA " fa
}
## model is in the third field, starting at the third character
## of a line which starts with "model"
## (so it does not match "extended model")
$1 == "model" && mo == "" {
mo = substr($3, 3)
##print "MO " mo
}
## stepping id is in field 4 starting at the third character
## of a line which contains "stepping id"
/stepping id/ && si == "" {
si = substr($4, 3)
##print "SI " si
}
## processor serial number is in field 4 starting at the third character
## of a line which contains "processor serial number:"
/processor serial number:/ && ps == "" {
ps = $4
##print "PS " ps
}
## Quit when we have all the values we need
em != "" && ef != "" && fa != "" && mo != "" && si != "" && ps != "" {
exit
}
END {
print em ef fa mo si " " ps
}
'