Monday, November 1, 2021

[SOLVED] Grep with RegEx Inside a Docker Container?

Issue

Dipping my toes into Bash coding for the first time (not the most experienced person with Linux either) and I'm trying to read the version from the version.php inside a container at:

/config/www/nextcloud/version.php

To do so, I run:

docker exec -it 1c8c05daba19 grep -eo "(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?" /config/www/nextcloud/version.php

This uses a semantic versioning RegEx pattern (I know, a bit overkill, but it works for now) to read and extract the version from the line:

$OC_VersionString = '20.0.1';

However, when I run the command it tells me No such file or directory, (I've confirmed it does exist at that path inside the container) and then proceeds to spit out the entire contents of the file it just said doesn't exist?

grep: (0|[1-9]\d*).(0|[1-9]\d*).(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-])(?:.(?:0|[1-9]\d|\d*[a-zA-Z-][0-9a-zA-Z-]))))?(?:+([0-9a-zA-Z-]+(?:.[0-9a-zA-Z-]+)*))?: No such file or directory /config/www/nextcloud/version.php:$OC_Version = array(20,0,1,1); /config/www/nextcloud/version.php:$OC_VersionString = '20.0.1'; /config/www/nextcloud/version.php:$OC_Edition = ''; /config/www/nextcloud/version.php:$OC_VersionCanBeUpgradedFrom = array ( /config/www/nextcloud/version.php: 'nextcloud' => /config/www/nextcloud/version.php: 'owncloud' => /config/www/nextcloud/version.php:$vendor = 'nextcloud';

Anyone able to spot the problem?

Update 1:

For the sake of clarity, I'm trying to run this from a bash script. I just want to fetch the version number from that file, to use it in other areas of the script.

Update 2:

Responding to the comments, I tried to login to the container first, and then run the grep, and still get the same result. Then I cat that file and it shows it's contents no problem.

enter image description here


Solution

Well, for any potential future readers, I had no luck getting grep to do it, I'm sure it was my fault somehow and not grep's, but thanks to the help in this post I was able to use awk instead of grep, like so:

docker exec -it 1c8c05daba19 awk '/^\$OC_VersionString/ && match($0,/\047[0-9]+\.[0-9]+\.[0-9]+\047/){print substr($0,RSTART+1,RLENGTH-2)}' /config/www/nextcloud/version.php

That ended up doing exactly what I needed:

  • It logs into a docker container.
  • Scans and returns just the version number from the line I am looking for at: /config/www/nextcloud/version.php inside the container.
  • Exits stage left from the container with just the info I needed.
  • I can get right back to eating my Hot Cheetos.


Answered By - J. Scott Elblein