0

I have a simple text file ./version containing a version number. Unfortunately, sometimes the version number in the file is followed by whitespaces and newlines like

1.1.3[space][space][newline]
[newline]
[newline]

What is the best, easiest and shortest way to extract the version number into a bash variable without the trailing spaces and newlines? I tried

var=`cat ./version | tr -d ' '`

which works for the whitespaces but when appending a tr -d '\n' it does not work.

Thanks, Chris

Chris
  • 981
  • 4
  • 14
  • 29

4 Answers4

2
$ echo -e "1.1.1  \n\n" > ./version
$ read var < ./version
$ echo -n "$var" | od -a
0000000   1   .   1   .   1
0000005
brian-brazil
  • 31,678
  • 6
  • 93
  • 86
2

Pure Bash, no other process:

echo -e "1.2.3  \n\n" > .version

version=$(<.version)
version=${version// /}

echo "'$version'"

result: '1.2.3'

Fritz G. Mehner
  • 16,550
  • 2
  • 34
  • 41
1

I still do not know why, but after deleting and recreating the version file this worked:

var=`cat ./version | tr -d ' ' | tr -d '\n'`

I'm confused... what can you do different when creating a text file. However, it works now.

Chris
  • 981
  • 4
  • 14
  • 29
  • 2
    You can do that with one call to tr by putting the space and newline inside square brackets: var=$(cat ./version | tr -d '[ \n]') – Dennis Williamson 0 secs ago [delete this comment] – Dennis Williamson Jun 10 '09 at 11:23
0

I like the pure version from fgm's answer.

I provide this one-line command to remove also other characters if any:

perl -pe '($_)=/([0-9]+([.][0-9]+)+)/' 

The extracted version number is trimmed/stripped (no newline or carriage return symbols):

$> V=$( bash --version | perl -pe '($_)=/([0-9]+([.][0-9]+)+)/' )
$> echo "The bash version is '$V'"
The bash version is '4.2.45'

I provide more explanation and give other more sophisticated (but still short) one-line commands in my other answer.

Community
  • 1
  • 1
oHo
  • 51,447
  • 27
  • 165
  • 200