簡體   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