I am trying to extract a value from a long string that may change over time. So for example the string could look something like this
....../filename-1.9.0.3.tar.gz"<....
And what I want to extract is the value between filename- and .tar.gz, essentially the file version (1.9.0.3 in this case). The reason I need to do it this way is because I may later run the command and the value will be 1.9.0.6 or 2.0.0.2 or something entirely different.
How can I do this? I'm currently only using grep, but I wouldn't mind using other utilities such as sed or awk or cut or whatever. To be perfectly clear, I need to extract only the file version part of the string, since it is very long (on both sides) everything else needs to be cut out somehow.
grep -P -o 'filename-\K.*?(?=\.tar\.gz)'
(with recent enough versions of PCRE)..*?
would be better than.*
if there may be more than one.tar.gz
per line. – Stéphane Chazelas Mar 01 '16 at 22:57grep -P -om1 ...
to stop at first match – don_crissti Mar 01 '16 at 23:03grep -Pom1
will print all the matches of the first matching line.echo abc | grep -Pom1 .
will printa
,b
andc
lines.pcregrep
doesn't support-m
, but supportspcregrep -o1 'filename-(.*?)\.tar\.gz'
andpcregrep -Mo1 '(?s)filename-(.*?)\.tar\.gz.*'
– Stéphane Chazelas Mar 01 '16 at 23:21