Search code examples
regexbashmacoscocoapodspodfile

Find and extract a number from a file


So I want to create script to update a version number.

The file contents look like this. I struggle to extract the number from the file. I want to extract and parse the number "58" The other numbers might also change. The file contents look like this.:

# Some more lines above
    pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :tag => '0.2.58'
# More lines below

My approach was to use grep -o Alamofire.git.*[0-9].[0-9].[0-9]+ ../Podfile

But this doesn't work. Is there any easy solution to this?


Solution

  • If you can use ggrep

    ggrep -oP 'Alamofire\.git.*[0-9]\.[0-9]\.\K[0-9]+' ../Podfile
    

    Output

    58
    

    Another option with awk and a bit more specific match setting the . and ' as a field separator:

    awk -F"[.']" '
    match ($0, /Alamofire\.git.*\047[0-9]+\.[0-9]+\.[0-9]+\047$/) {
      print $(NF-1)
    }' file
    

    Or with gnu-awk and a capture group:

    gawk 'match($0, /Alamofire\.git.*[0-9]\.[0-9]\.([0-9]+)/, a) {print a[1]}' ../Podfile