1

I am new to scripting and I have a task which consists of extracting a version from a LOC and save it to $VERSION. The line looks like this:

#define PROJECT_VERSION "21.02"

I have to extract "21.02" and save it in $VERSION, using bash. Right now, I am using the following command:

awk '/PROJECT_VERSION/{print $NF}' common/ESUtils.cpp

but it return more strings. Can you help me?

2
  • I have just seen that in order to print the 3rd field I have to use $3F. Commented Apr 6, 2021 at 9:54
  • awk '/PROJECT_VERSION/{print $NF}' file should work for you, what is but it return more strings you are getting in output? Please explain it more. Commented Apr 6, 2021 at 9:58

3 Answers 3

1

You can also consider using

awk '$2 == "PROJECT_VERSION"{print $3; exit}' common/ESUtils.cpp

That will find the first record wih Field 2 equal to PROJECT_VERSION and output Field 3 value, and exit right after it without looking further in the input file.

See an online demo:

#!/bin/bash
s='#define PROJECT_VERSION      "21.02"
1 PROJECT_VERSION   "22.02"'
awk '$2 == "PROJECT_VERSION"{print $3; exit}' <<< "$s"
# => "21.02"
Sign up to request clarification or add additional context in comments.

Comments

1

Using sed:

VERSION=$(sed -En '/PROJECT_VERSION/s/(^.*\")([[:digit:]]+\.[[:digit:]]+)(\".*$)/\2/p' project.cpp)

Enable regular expression interpretation with -E and then search for the line with "PROJECT_VERSION". With this line, split the line into 3 sections specified in parenthesis and substitute the line for the second section only, printing the result.

Comments

0

The answer would be:

VERSION=`awk '/PROJECT_VERSION/{print $3F}' project.cpp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.