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

4 Answers 4

2
$ echo -e "1.1.1  \n\n" > ./version
$ read var < ./version
$ echo -n "$var" | od -a
0000000   1   .   1   .   1
0000005
Sign up to request clarification or add additional context in comments.

Comments

2

Pure Bash, no other process:

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

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

echo "'$version'"

result: '1.2.3'

Comments

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.

1 Comment

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]
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.