I have a Makefile, that has variables version and build (those are not the only variables, and can be defined in different order). Using only sed, I’d like to combine the values into a single version string.
So far I’ve got:
sed -n -e '/=/{s/version.*=\(.*\)/\1\./p;s/build.*=\(\d*\)*/\1/p}' Makefile
but both values are separated by newline. The above produces following output:
0.8.2. 1
I’d like:
0.8.2.1
I tried N, but couldn’t figure how to use it in this sitation.
Why ‘sed only’ restriction? I’d like to learn it, and that is the best way for me.
Standalone sample:
sed -n -e '/=/ {s/version.*=\(.*\)/\1\./p;s/build.*=\(\d*\)*/\1/p}' <<EOF
foo=1
version=0.8.2
bar=2
build=1
bam=bug-AWWK
EOF
The following are all based on the same idea: store the version and build numbers, then print them at the end of input.
When it comes to storage, sed has the pattern space, which starts with the value of the current line, and a hold space, which can be used to save values for the duration of the process. The version should be wind up prepended to the value in the hold space, which can be accomplished by appending the hold space to the pattern space with
G. The build should be appended to the hold space, which can be done withH. To remove the newline thatHcreates, the hold space is moved back to the pattern space. In both cases, the newline created by theGandHis removed with as///, then back to the hold space withh. The end of input is signified by the$address, at which the hold space is moved back into the pattern space and printed. It’s shorter to see:This produces a newline at the end of the string, but hopefully that won’t be an issue.
The awk family of utilities support variables, making the task more straightforward. They have the special variables OFS, the output field separator, and ORS, the output record separator. awk’s
printoutputs the OFS between each argument, and ORS at the end. The special patternENDmatches after the end of input.If you don’t care about the trailing dot and can be certain of the order of the version and build lines in the makefile:
Continuing upwards in expressiveness of language is perl. perl’s
ENDhas a similar function to awk’s, marking a block to be run at the end of the process. A hash can be used to store the parts of the complete version number, allowing the lines to match and store the version and build to be combined into a single line.While using sed makes for an interesting exercise, the value in exercises is strengthening yourself by doing them. If you must turn to others, it’s better not to focus on how you’re trying to solve the problem but instead find out recommended approaches. You’ll learn more.