1

Using bash script I need to search string like version = '1.8.1-SNAPSHOT' from text file and get value '1.8.1-SNAPSHOT' into variable.

I tryed to use the next code, but no result:

version=$(grep -P "version\s?=\s?'([a-zA-Z.\d-]){5,20}?'" file.txt) 
regex="'([a-zA-Z.\d-]){5,30}?'"
value=`expr match "$version" '([a-zA-Z.\d-]){5,30}?'`

What is wrong and are there another way?

Some of text file:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath('org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE')
    }
}

springBootVersion = '2.0.7.RELEASE'


apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

// for Glassfish
//apply plugin: 'war'

jar {
    baseName = 'work-space'
    version = '1.8.1-SNAPSHOT'
}

Desired string need to be '1.8.1-SNAPSHOT' into variable for the next manipulation.

5
  • Try version="$(grep -oP "version\s*=\s*'\K[^']+" file)". See ideone.com/LtxK2g Commented Dec 16, 2018 at 10:09
  • Thanks, but i also need to get from version = '1.8.1-SNAPSHOT' the finish result like '1.8.1-SNAPSHOT' Commented Dec 16, 2018 at 10:11
  • Show file.txt and desired string. Commented Dec 16, 2018 at 10:12
  • ideone.com/LtxK2g shows the 1.8.1-SNAPSHOT - isn't it expected? Commented Dec 16, 2018 at 10:13
  • Yes! Awesome! Thanks! Commented Dec 16, 2018 at 10:23

1 Answer 1

4

You may use

version="$(grep -oP "version\s*=\s*'\K[^']+" file)"

See the online demo.

As you are using P option, I assume you may use PCRE regex with your grep. To output the match, you also need to add o option.

The regex you need is version\s*=\s*'\K[^']+:

  • version - matches version substring
  • \s*=\s* - = enclosed with 0+ whitespaces
  • ' - a ' char
  • \K - match reset operator discarding all text matched so far
  • [^']+ - 1 or more chars other than '
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.