Search code examples
shellawksedtext-parsing

Extract a string from a file and store it in a variable


I have a file that has the below line in it.

ARG VERSION="6.0.0" // Here 6.0.0 is the version and could be any number.

I have a need to extract this value 6.0.0 and store it as a shell variable to be later used in the build.

Is there a way to achieve this?


Solution

  • Could you please try following.

    awk 'match($0,/ARG VERSION="[^"]*/){print substr($0,RSTART+13,RLENGTH-13)}' Input_file
    

    Explanation: Adding detailed explanation for above.

    awk '                                      ##Starting awk program from here.
    match($0,/ARG VERSION="[^"]*/){            ##Using match function to match regex ARG VERSION=" till " here.
      print substr($0,RSTART+13,RLENGTH-13)    ##Printing sub-string of current line starting point is RSTART ending point is RLENGTH.
    }
    ' Input_file                               ##Mentioning Input_file name here.