Search code examples
linuxgrep

How to grep my one-line file with constant key?


This is my file

__version__="1.11.10"

numerical part will change all the time and I want to grep this.

new_tag=`grep -Eo '[0-9]+\.[0-9]+\.[0-9]+'_version.py`

failed. how to extract 1.11.10 ?


Solution

  • You may use sed:

    sed -n 's/.*="\([^"]*\)"/\1/p' file
    

    To assign to a variable:

    new_tag=$(sed -n 's/.*="\([^"]*\)"/\1/p' file)
    

    See the online Bash demo.

    Details

    • -n - suppresses default line output in the sed command
    • .*="\([^"]*\)" - a POSIX BRE pattern that matches
      • .* - any text then
      • =" - a =" string
      • \([^"]*\) - capturing group #1 that captures zero or more chars other than "
      • " - a " char
    • \1 - replaces the match with Group 1 contents
    • p - prints the resulting value