[英]How to filter shell output to only number with decimal?
I have CI/CD Config which required python version to be set to default by pyenv.我有 CI/CD 配置,需要 pyenv 将 python 版本设置为默认值。 I want to
python2 -V
output showed up with only, example, 2.7.18.我想
python2 -V
output 仅显示 2.7.18。 But, rather than showing 2.7.18, it showing full text Python 2.7.18
.但是,它不是显示 2.7.18,而是显示全文
Python 2.7.18
。
But, when I use it in python3 python -V
, it showed the correct & current python3 version ( 3.9.0
).但是,当我在 python3
python -V
中使用它时,它显示了正确的当前 python3 版本( 3.9.0
)。
I use this code to try showing numbers only: $(python -V | grep -Eo '[0-9]\.[0-9]\.[10-19]')
.我使用此代码尝试仅显示数字:
$(python -V | grep -Eo '[0-9]\.[0-9]\.[10-19]')
。
And to set default with pyenv: pyenv global $(python3 -V | grep -Eo '[0-9]\.[0-9]\.[10-19]') $(python -V | grep -Eo '[0-9]\.[0-9]\.[10-19]')
并使用 pyenv 设置默认值:
pyenv global $(python3 -V | grep -Eo '[0-9]\.[0-9]\.[10-19]') $(python -V | grep -Eo '[0-9]\.[0-9]\.[10-19]')
So pyenv $(python3 version) $(python2 version)
所以
pyenv $(python3 version) $(python2 version)
Here is the image:这是图像:
Image of wrong output错误 output 的图像
Thanks!谢谢!
A simple way would be to just replace the string Python with the emtpy string, if it exists.一种简单的方法是将字符串 Python 替换为空字符串(如果存在)。
Here a quick one-liner这是一个快速的单线
python -V 2>&1| sed -e "s/Python//g" | xargs
That would print the python version, redirects stderr to stdout, replaces "Python" with "".这将打印 python 版本,将标准错误重定向到标准输出,将“Python”替换为“”。 Xargs without parameters returns the trimmed input string.
不带参数的 Xargs 返回修剪后的输入字符串。
Here are a few more ways to get the version number:这里还有一些获取版本号的方法:
# Print 1 word per line, the select the last word:
python -V 2>&1 | xargs -n1 | tail -n1
# Print the last word:
python -V 2>&1 | perl -lane 'print $F[-1];'
# Print the first stretch of 1 or more { digits or periods }:
python -V 2>&1 | grep -Po '[\d.]+'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.