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
我有一个包含版本号的简单文本文件./version。不幸的是,有时文件中的版本号后面跟着空格和换行符
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
在没有尾随空格和换行符的情况下将版本号提取到bash变量中的最佳,最简单和最短的方法是什么?我试过了
var=`cat ./version | tr -d ' '`
which works for the whitespaces but when appending a tr -d '\n'
it does not work.
这适用于空格,但当附加tr -d'\ n'时它不起作用。
Thanks, Chris
4 个解决方案
#1
$ echo -e "1.1.1 \n\n" > ./version
$ read var < ./version
$ echo -n "$var" | od -a
0000000 1 . 1 . 1
0000005
#2
Pure Bash, no other process:
Pure Bash,没有其他过程:
echo -e "1.2.3 \n\n" > .version
version=$(<.version)
version=${version// /}
echo "'$version'"
result: '1.2.3'
#3
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.
我很困惑......创建文本文件时你能做些什么呢?但是,它现在有效。
#4
I like the pure bash version from fgm's answer.
我喜欢fgm答案的纯粹bash版本。
I provide this one-line perl command to remove also other characters if any:
我提供这个单行perl命令来删除其他字符,如果有的话:
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 perl commands in my other answer.
我在其他答案中提供了更多解释并给出了其他更复杂(但仍然很短)的单行perl命令。
#1
$ echo -e "1.1.1 \n\n" > ./version
$ read var < ./version
$ echo -n "$var" | od -a
0000000 1 . 1 . 1
0000005
#2
Pure Bash, no other process:
Pure Bash,没有其他过程:
echo -e "1.2.3 \n\n" > .version
version=$(<.version)
version=${version// /}
echo "'$version'"
result: '1.2.3'
#3
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.
我很困惑......创建文本文件时你能做些什么呢?但是,它现在有效。
#4
I like the pure bash version from fgm's answer.
我喜欢fgm答案的纯粹bash版本。
I provide this one-line perl command to remove also other characters if any:
我提供这个单行perl命令来删除其他字符,如果有的话:
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 perl commands in my other answer.
我在其他答案中提供了更多解释并给出了其他更复杂(但仍然很短)的单行perl命令。