Borisw37
Borisw37

Reputation: 759

Get data from a text file using shell script

I have a text file that on one of the lines contains "#define VERSION_NUMBER 0011" I need to find that line and assign the 4 digit value "0011" to a variable.

Upvotes: 0

Views: 2111

Answers (2)

cptaffe
cptaffe

Reputation: 426

I would use grep and regex, once grep returns a value, you can assign that value to a bash variable fairly easily. Following is working test code:

$ echo "#define VERSION_NUMBER 0011" > test.c $ c=`cat test.c | sed -n -e 's/^#define VERSION_NUMBER \([0-9]\{4\}\)$/\1/p'` $ echo $c 0011

Broken Down

This is the important line:

c=`cat test.c | sed -n -e 's/^#define VERSION_NUMBER \([0-9]\{4\}\)$/\1/p'`

Broken down it is composed of c, the variable name is assigned to the evaluation (`...`) of the sed command. The sed command is where the regex is. What I came up with is:

  • ^: the line starts with
  • #define VERSION_NUMBER: a text literal, this will be character-for-character in the string.
  • \(...\): an escaped set of parens that make up a match portion.
  • [0-9]: in the match, a number exists (0 to 9).
  • \{4\}: the preceding number repeats 4 times exactly.
    • you could use * here for any number of matches, \{4,\} for 4 or more, or \{4,6\} for 4-6 matches.
  • $: end of the line

When this is run, sed emits the number, and since we assigned sed's evaluation to c, c now contains that number.

Issues

Possible issues are that this does not take whitespace into account, if there is a tab or space at the beginning or end of this line, it will fail.

Confession: I had to learn a little unix regex to answer this, reference: smugbook.

Upvotes: 0

Xavier Shay
Xavier Shay

Reputation: 4127

VAR=$(cat file | grep "#define VERSION_NUMBER" | awk '{print $3}')

This does seem kind of backwards though. Is it possible to change your build scripts to pass -DVERSION_NUMBER=0011 and define the version number that way? Then it can be stored in a simple language independent text file containing nothing else.

Upvotes: 1

Related Questions