linux – find and assign a string to a variable in bash

linux – find and assign a string to a variable in bash

version=$(grep ^version version.txt | cut -d -f2)

You can use one of one of the following commands and assign the result to a variable:

INPUT:

$ cat version.txt 
abc
version = 0.0.1-SNAPSHOT
123

grep:

$ grep -oP (?<=^versions=s)[^]* version.txt                                                                                
0.0.1-SNAPSHOT

perl:

$ perl -ne if(/^version/){s/^versions*=s*|//g; print} version.txt                                                           
0.0.1-SNAPSHOT

There are many other ways of reaching your result (sed,awk,…)

Explanations:

1) You use grep in perl mode and use lookbehind assertion, in this case I have supposed that your equal is always surrounded by 1 and only 1 space

2) The perl approach is more flexible (0,1 or more spaces can be located around the equal character), here the principle is that you identify the line starting with version, then you remove the version = and double quotes before printing the result.

linux – find and assign a string to a variable in bash

var=$(awk /version/ {print $3} file.txt)

/EXPR/ <- You can use a regex like expression with awk.
$3 since we are interested in the third column, you could also use this code:

var=$(awk /version/ {print $(NF)} file.txt)

NF in awk is the number of fields of the current line, in this case 3.

Leave a Reply

Your email address will not be published. Required fields are marked *