Harshit Goel
Harshit Goel

Reputation: 185

How to find a substring from some text in a file and store it in a bash variable?

I have a file named config.txt which has following data:

ABC_PATH=xxx/xxx
IMAGE=docker.name.net:3000/apache:1.8.109.1
NAMESPACE=xxx

Now I am running a shell script in which I want to store 1.8.109.1 (this value may differ, rest will remain same) in a variable, maybe using sed, awk or any other linux tool. How can I achieve that?

Upvotes: 0

Views: 1799

Answers (2)

ennk
ennk

Reputation: 36

The following will work.

ver="$(cat config.txt | grep apache: | cut -d: -f3)"

grep apache: will find the line that has the text 'apache:' in it.

-d specifies what delimiters to use. In this case : is set as the delimiter. -f is used to select the specific field (array index, starting at 1) of the resulting list obtained after delimiting by :

Thus, -f3 selects the 3rd occurence of the delimited list.

The version info is now captured in the variable $ver

Upvotes: 2

Markante Makrele
Markante Makrele

Reputation: 108

I think this should work:

cat config.txt | grep apache: | cut -d: -f3

Upvotes: 0

Related Questions