Bash scripting - how to concatenate the following strings?
In one go:
printf '%s%s\n' "$(grep -Pom1 'extended model.*\(\K\d+' <(cpuid))" \
"$(grep -Pom1 'extended family.*\(\K\d+' <(cpuid))"
The above leverages process substitution (<()
), and command substitution ($()
).
The two command substitutions are replaced with the STDOUT of the commands inside
cpuid
command is put inside process substitution, the STDOUT will be returned as a file descriptor,grep
will do the necessary matching on it, we have usedgrep
with PCRE (-P
) to get only (-o
) the desired portion, and-m1
will stop after first match to avoid repetitionprintf
is used to get the output in desired format
Example:
$ printf '%s%s\n' "$(grep -Pom1 'extended model.*\(\K\d+' <(cpuid))" "$(grep -Pom1 'extended family.*\(\K\d+' <(cpuid))"
30
You can avoid the intermediate file by using a pipe, and you can avoid using both sed
and awk
by doing your matching and substitution in awk
e.g.
/usr/bin/cpuid |
awk '/extended model/ {mod = substr($4,3)} /extended family/ {fam = substr($4,3)}
END {printf "%d%d\n", mod, fam}'
Without making assumptions and changing the nature of the sample, here is a drop in replacement that stores the output in a variable as requested:
CPUID=$(/usr/bin/cpuid)
a=$(echo "$CPUID" | grep 'extended model' | sed 's/0x//' | awk ' { print $4 } ')
a+=$(echo "$CPUID" | grep 'extended family' | sed 's/0x//' | awk ' { print $4 } ')
First line sets the variable CPUID
to the output of /usr/bin/cpuid
I then set the variable a
to be the output (echo
) of the CPUID
variable set in the line above (this is then piped to your provided commands).