如何 grep 句子中的任意數字

如何 grep 句子中的任意數字

你能幫我 grep 嗎?我有一個:

variable="RMN quota:        0 bytes"

variable="RMN quota:        1.56 bytes"

若要取得輸出的目標 ID:0 或 1.56。

grep 會做什麼呢?

答案1

POSIXly:

n=${variable% bytes} # strip the trailing " bytes"
n=${n##*[[:blank:]]} # strip the leading part up to the rightmost blank

答案2

這似乎有效:

grep -Eo '[0-9]+(\.[0-9]+)?' inputfile  

如果您要檢查 shell 變數的值而不是檔案的內容,您可以這樣做:

echo "$variable" | grep -Eo '[0-9]+(\.[0-9]+)?'

答案3

既然你有 bash:

tr -d -c 0-9. <<<$variable

(也可以在 Zsh 中工作)。

相關內容