Issue
I am having trouble figuring out how to grep the characters between two single quotes .
I have this in a file
version: '8.x-1.0-alpha1'
and I like to have the output like this (the version numbers can be various):
8.x-1.0-alpha1
I wrote the following but it does not work:
cat myfile.txt | grep -e 'version' | sed 's/.*\?'\(.*?\)'.*//g'
Thank you for your help.
Addition:
I used the sed command sed -n "s#version:\s*'\(.*\)'#\1#p"
I also like to remove 8.x- which I edited to sed -n "s#version:\s*'8.x-\(.*\)'#\1#p"
.
This command only works on linux and it does not work on MAC. How to change this command to make it works on MAC?
sed -n "s#version:\s*'8.x-\(.*\)'#\1#p"
Solution
Try something like this: sed -n "s#version:\s*'\(.*\)'#\1#p" myfile.txt
. This avoids the redundant cat
and grep
by finding the "version" line and extracting the contents between the single quotes.
Explanation:
the -n
flag tells sed not to print lines automatically. We then use the p
command at the end of our sed pattern to explicitly print when we've found the version line.
Search for pattern: version:\s*'\(.*\)'
version:\s*
Match "version:" followed by any amount of whitespace'\(.*\)'
Match a single'
, then capture everything until the next'
Replace with: \1
; This is the first (and only) capture group above, containing contents between single quotes.
Answered By - John