[英]How to check if a string only contains digits/numerical characters
如何檢查MyVar
是否僅包含帶有 BASH if
語句的數字。我指的是 0-9 的數字。
IE:
if [[ $MyVar does contain digits ]] <-- How can I check if MyVar is just contains numbers
then
do some maths with $MyVar
else
do a different thing
fi
這里是:
#!/bin/bash
if [[ $1 =~ ^[0-9]+$ ]]
then
echo "ok"
else
echo "no"
fi
如果第一個參數只包含數字,則打印ok
,否則no
打印。 你可以用: ./yourFileName.sh inputValue
來調用它
[[ $myvar =~ [^[:digit:]] ]] || echo All Digits
或者,如果您喜歡if-then
表單:
if [[ $myvar =~ [^[:digit:]] ]]
then
echo Has some nondigits
else
echo all digits
fi
在過去,我們會使用[0-9]
。 這種形式不是unicode安全的。 現代的unicode-safe替代品是[:digit:]
。
如果您想以符合POSIX的方式進行測試,可以使用以下任一方法:
expr string : regex ## returns length of string if both sides match
要么
expr match string regex ## behaves the same
例如,測試$myvar
是否全是數字:
[ $(expr "x$myvar" : "x[0-9]*$") -gt 0 ] && echo "all digits"
注意: 'x'
前置於變量和表達式以防止測試空字符串拋出錯誤。 要使用測試返回的length
,請不要忘記減1
代表'x'
。
在if-then-else
表單中,這是一個簡短的腳本,用於測試腳本的第一個參數是否包含所有數字:
#!/bin/sh
len=$(expr "x$1" : "x[0-9]*$") ## test returns length if $1 all digits
let len=len-1 ## subtract 1 to compensate for 'x'
if [ $len -gt 0 ]; then ## test if $len -gt 0 - if so, all digits
printf "\n '%s' : all digits, length: %d chars\n" "$1" $len
else
printf "\n '%s' : containes characters other than [0-9]\n" "$1"
fi
示例輸出
$ sh testdigits.sh 265891
'265891' : all digits, length: 6 chars
$ sh testdigits.sh 265891t
'265891t' : contains characters other than [0-9]
bash正則表達式測試[[ $var =~ ^[0-9]+$ ]]
很好,我使用它,但它是一種基礎 (僅限於bash shell)。 如果您關心可移植性,POSIX測試將適用於任何符合POSIX標准的shell。
簡單! 只需在grep中使用表達式選項下面的解決方案echo是變量並檢查它是否只包含數字
if [[ $(echo $var | grep -E "^[[:digit:]]{1,}$") ]]
then
echo "var contains only digits"
else
echo "var contains other characters apart from digits"
fi
Grep表達式解決方案沒有[[]],更寬的外殼兼容性:
if [ "$(echo $var | grep -E "^[0-9]{1,}$")" ]; then echo "digits only"; then
echo "var contains digits only"
else
echo "var contains digits and/or other characters"
fi
對於 Bash,另一種可能比正則表達式匹配更便宜的選擇(我沒有進行性能測試)是使用pattern substitution
將所有數字替換為空字符串,並測試結果字符串是否為空。
if [[ -z ${var//[0-9]} ]]; then # or ${var//[[:digit:]]}
echo "only digits"
else
echo "not only digits"
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.