-1

I have a file that has a line stating

version = "12.0.08-SNAPSHOT"

The word version and quoted strings can occur on multiple lines in that file.

I am looking for a single line bash statement that can output the following string:

12.0.08-SNAPSHOT

The version can have RELEASE tag too instead of SNAPSHOT.

So to summarize, given

version = "12.0.08-SNAPSHOT"
expected output: 12.0.08-SNAPSHOT

And given

version = "12.0.08-RELEASE"
expected output: 12.0.08-RELEASE
Nik
  • 5,515
  • 14
  • 49
  • 75

3 Answers3

9

The following command prints strings enquoted in version = "...":

grep -Po '\bversion\s*=\s*"\K.*?(?=")' yourFile

-P enables perl regexes, which allow us to use features like \K and so on.
-o only prints matched parts instead of the whole lines.

\b ensures that version starts at a word boundary and we do not match things like abcversion.
\s stands for any kind of whitespace.
\K lets grep forget, that it matched the part before \K. The forgotten part will not be printed.
.*? matches as few chararacters as possible (the matching part will be printed) ...
(?=") ... until we see a ", which won't be included in the match either (this is called a lookahead).

Not all grep implementations support the -P option. Alternatively, you can use perl, as described in this answer:

perl -nle 'print $& if m{\bversion\s*=\s*"\K.*?(?=")}' yourFile
Community
  • 1
  • 1
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • `grep -P` works with GNU grep (most versions anyway), but it's not portable. The OP didn't specify what operating system is being used, so it's important to qualify your answer if it is platform-specific. Or even better, make a portable answer. – ghoti Apr 26 '17 at 21:26
  • very nice answer! – clt60 Apr 26 '17 at 22:13
2

Seems like a job for cut:

$ echo 'version = "12.0.08-SNAPSHOT"' | cut -d'"' -f2
12.0.08-SNAPSHOT

$ echo 'version = "12.0.08-RELEASE"' | cut -d'"' -f2
12.0.08-RELEASE
I0_ol
  • 1,054
  • 1
  • 14
  • 28
1

Portable solution:

$ echo 'version = "12.0.08-RELEASE"' |sed -E 's/.*"(.*)"/\1/g'
12.0.08-RELEASE

or even:

$ perl -pe 's/.*"(.*)"/\1/g'.
$ awk -F"\"" '{print $2}'
George Vasiliou
  • 6,130
  • 2
  • 20
  • 27