tags:

views:

520

answers:

3

Hi all

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

+1  A: 
$ echo -e "1.1.1  \n\n" > ./version
$ read var < ./version
$ echo -n "$var" | od -a
0000000   1   .   1   .   1
0000005
A: 

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
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
A: 

Pure Bash, no other process:

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

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

echo "'$version'"

result: '1.2.3'

fgm