Search code examples
regexshellash

Extracting subsequence from expression matching pattern with /bin/ash


I wanted to automatize tagging of my artifacts, and I've written a simple shell script that extracts the version from the git tag (that matches the pattern):

#!/bin/sh
regex="^RELEASE-(.*)$"
if [[ $1 =~ $regex ]]; then
 echo -n "${BASH_REMATCH[1]}"
 exit 0
else
 exit 1 
fi

Then I've got errors when building with docker:latest image, after some struggling I've found out, that, for whatever reason, this image doesn't have /bin/bash, they prefer /bin/ash instead.

The problem is, that I haven't found any replacement for regex operator in ash. After googling I've found suggestion to do that with sed, just like:

echo -n "RELEASE-1.0.0" | sed 's/^RELEASE-\(.*\)$/\1/'

However, that example fails epically, because it prints the whole input if regex doesn't match...

Is there any reasonable replacement/fix for that regex match operator?


Solution

  • Try running modified version that will only print on matches:

    echo -n "RELEASE-1.0.0" | sed -n 's/^RELEASE-\(.*\)$/\1/p'
    

    The '-n' sed option, and the '/p' option to 's' command will print only if substitution was performed