Home > Operation and Maintenance > Linux Operation and Maintenance > How to determine whether a string is a number in Linux

How to determine whether a string is a number in Linux

青灯夜游
Release: 2022-03-02 14:21:31
Original
5567 people have browsed it

判断方法:1、用“"$值"|[-n "`sed -n '/^[0-9][0-9]*$/p'`"]”语句;2、用“grep '^[[:digit:]]*$'<<< "$值"”语句;3、用["$值" -gt 0] 2>/dev/null”语句。

How to determine whether a string is a number in Linux

本教程操作环境:linux5.9.8系统、Dell G3电脑。

linux shell 判断字符串是否为数字

方法1

a=1234
echo "$a"|[ -n "`sed -n &#39;/^[0-9][0-9]*$/p&#39;`" ] && echo string a is numbers
Copy after login

第一个-n是shell的测试标志,对后面的串"`sed -n &#39;/^[0-9][0-9]*$/p&#39;`" 进行测试,如果非空,则结果为真。

sed默认会显示所有输入行信息的,sed 的“-n”选项是让sed不要显示,而只显示我们所需要的内容:即后面的表达式所匹配的行,这是通过表达式中加入“p”命令来实现的。

/^[0-9][0-9]*$/ 含义是匹配至少由一位数字构成的行

方法2

if grep &#39;^[[:digit:]]*$&#39; <<< "$1";then 
      echo "$1 is number." 
else 
      echo &#39;no.&#39; 
fi
Copy after login

方法3

if [ "$1" -gt 0 ] 2>/dev/null ;then 
      echo "$1 is number." 
else 
      echo &#39;no.&#39; 
fi
Copy after login

方法4

case "$1" in 
  [1-9][0-9]*)  
    echo "$1 is number." 
    ;; 
  *)  
    ;; 
esac
Copy after login

方法5

echo $1| awk &#39;{print($0~/^[-]?([0-9])+[.]?([0-9])+$/)?"number":"string"}&#39;

if [ -n "$(echo $1| sed -n "/^[0-9]\+$/p")" ];then 
  echo "$1 is number." 
else 
  echo &#39;no.&#39; 
fi
Copy after login

方法6

expr $1 "+" 10 &> /dev/null
if [ $? -eq 0 ];then
  echo "$1 is number"
else
  echo "$1 not number"
fi
Copy after login

相关推荐:《Linux视频教程

The above is the detailed content of How to determine whether a string is a number in Linux. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template