user2366975
user2366975

Reputation: 4720

sed extract substring between two characters from a file and save to variable

I am automatically building a package. The automated script needs to get the version of the package to build. I need to get the string of the python script main.py. It says in line 15

VERSION="0.2.0.4" #DO NOT MOVE THIS LINE

I need the 0.2.0.4, in future it can easily become 0.10.3.15 or so, so the sed command must not have a fixed length. I found this on stackoverflow:

sed -n '15s/.*\#\([0-9]*\)\/.*/\1/p'

"This suppresses everything but the second line, then echos the digits between # and /"

This does not work (adjusted). Which is the last "/"? How can I save the output into a variable called "version"?

version = sed -n ... 

throws an error

command -n not found

Upvotes: 0

Views: 1613

Answers (4)

devnull
devnull

Reputation: 123658

Try:

sed -n '15s/[^"]*"\(.*\)".*/\1/p' inputfile

In order to assign it to a variable, say:

VARIABLE=$(sed -n '15s/[^"]*"\(.*\)".*/\1/p' inputfile)

In order to remove the dependency that the VERSION would occur only on line 15, you could say:

sed -n '/^VERSION=/ s/[^"]*"\(.*\)".*/\1/p' inputfile

Upvotes: 1

Jotne
Jotne

Reputation: 41460

If you just need version number.

awk -F\" 'NR==15 {print $2}' main.py

This prints everything between " on line 15. Like 0.2.0.4

Upvotes: 4

fedorqui
fedorqui

Reputation: 290415

With awk:

$ awk -F= 'NR==15 {gsub("\"","",$2); print $2}' main.py
0.2.0.4

Explanation

  • NR==15 performs actions on line number 15.
  • -F= defines the field separator as =.
  • {gsub("\"","",$2); print $2} removes the " character on the 2nd field and prints it.

Update

to be more specific the line is version="0.2.0.4" #DO NOT MOVE THIS LINE

$ awk -F[=#] 'NR==15 {gsub("\"","",$2); print $2}' main.py
0.2.0.4 

Using multiple field separator -F[=#] which means it can be either # or =.

To save it into your version variable, use the expression var=$(command) like:

version=$(awk -F[=#] 'NR==15 {gsub("\"","",$2); print $2}' main.py)

Upvotes: 1

Srini V
Srini V

Reputation: 11375

there should not be space in assigning variables

version=$(your code)

version=$(sed -r -i '15s/.*\"\([0-9]*\)\/.*/"/p' main.py)

OR

version=`sed -r -i '15s/.*\"\([0-9]*\)\/.*/"/p' main.py`

Upvotes: 0

Related Questions