繁体   English   中英

如何将 shell output 过滤为仅带小数的数字?

[英]How to filter shell output to only number with decimal?

我有 CI/CD 配置,需要 pyenv 将 python 版本设置为默认值。 我想python2 -V output 仅显示 2.7.18。 但是,它不是显示 2.7.18,而是显示全文Python 2.7.18

但是,当我在 python3 python -V中使用它时,它显示了正确的当前 python3 版本( 3.9.0 )。

我使用此代码尝试仅显示数字: $(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]')

所以pyenv $(python3 version) $(python2 version)

这是图像:

错误 output 的图像

谢谢!

一种简单的方法是将字符串 Python 替换为空字符串(如果存在)。

这是一个快速的单线

python -V 2>&1| sed -e "s/Python//g" | xargs

这将打印 python 版本,将标准错误重定向到标准输出,将“Python”替换为“”。 不带参数的 Xargs 返回修剪后的输入字符串。

这里还有一些获取版本号的方法:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM