sagioto
sagioto

Reputation: 261

Getting max version by file name

I need to write a shell script that does the following:

  1. In a given folder with files that fit the pattern: update-8.1.0-v46.sql I need to find the maximum version
  2. I need to write the maximum version I've found into a configuration file

For 1, I've found the following answer: Shell script: find maximum value in a sequence of integers without sorting The only problem I have is that I can't get down to a list of only the versions, I tried:

ls | grep -o "update-8.1.0-v\(\d*\).sql"

but I get the entire file name in return and not just the matching part Any ideas? Maybe move everything to awk?

I ended up using:

SCHEMA=`ls database/targets/oracle/ | grep -o "update-$VERSION-v.*.sql" | sed "s/update-$VERSION-v\([0-9]*\).sql/\1/p" | awk '$0>x{x=$0};END{print x}'`

based on dreamer's answer

Upvotes: 1

Views: 303

Answers (2)

MattLBeck
MattLBeck

Reputation: 5831

grep isn't really the best tool for extracting captured matches, but you can use look-behind assertions if you switch it to use perl-like regular expressions. Anything in the assertion will not be printed when using the -o flag.

ls | grep -Po "(?<=update-8.1.0-v)\d+"
46

Upvotes: 0

Ankit Kumar
Ankit Kumar

Reputation: 1463

you can use sed for this:

echo "update-8.1.0-v46.sql" | sed 's/update-8.1.0-v\([0-9]*\).sql/\1/p'

The output in this case will be 46

Upvotes: 2

Related Questions