簡體   English   中英

從bash shell中的字符串返回數字

[英]Return digits from a string in bash shell

我想只返回bash shell中字符串變量的數字。 例如,對於:

#!/bin/sh
file="./file_02.txt"
file_num_tag=?????????????????
echo $file_num_tag

...我想回來

>>> 02

我知道這是非常微不足道的,但我很困惑自己尋找答案,我想知道最好的方法。

您可以使用此BASH字符串替換:

file="./file_02.txt"
echo "${file//[^[:digit:]]}"
02

[^[:digit:]]將匹配並刪除字符串file中的所有非數字。

或使用tr (如果不使用BASH):

num=`echo "$file" | tr -cd '[[:digit:]]'`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM