/dev/null" statement."/> /dev/null" statement.">

Home>Article>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

青灯夜游
青灯夜游 Original
2022-03-02 14:21:31 5381browse

判断方法:1、用“"$值"|[-n "`sed -n '/^[0-9][0-9]*$/p'`"]”语句;2、用“grep '^[[:digit:]]*$'48da3d3ec813251e06343be78ebfa30d/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 '/^[0-9][0-9]*$/p'`" ] && echo string a is numbers

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

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

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

方法2

if grep '^[[:digit:]]*$' <<< "$1";then echo "$1 is number." else echo 'no.' fi

方法3

if [ "$1" -gt 0 ] 2>/dev/null ;then echo "$1 is number." else echo 'no.' fi

方法4

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

方法5

echo $1| awk '{print($0~/^[-]?([0-9])+[.]?([0-9])+$/)?"number":"string"}' if [ -n "$(echo $1| sed -n "/^[0-9]\+$/p")" ];then echo "$1 is number." else echo 'no.' fi

方法6

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

相关推荐:《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!

Statement:
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