BASH:字符串测试是否有效作为整数? [英] BASH: Test whether string is valid as an integer?
问题描述
我试图做的共同之处就够了:在shell脚本解析用户输入。如果用户提供了一个有效的整数,剧本做一件事情,如果没有有效的,但它确实别的东西。麻烦的是,我还没有发现这样做的一个简单的(和合理的优雅的)的方式 - 我不希望有成炭挑它除了字符
我知道这一定是容易的,但我不知道怎么办。我能做到这一点的十几种语言,但不是BASH!
在我的研究,我发现这一点:
<一个href=\"http://stackoverflow.com/questions/136146/regular-ex$p$pssion-to-test-whether-a-string-consists-of-a-valid-real-number-in-ba\">http://stackoverflow.com/questions/136146/regular-ex$p$pssion-to-test-whether-a-string-consists-of-a-valid-real-number-in-ba
和有一个其中的答案谈到有关正则表达式,但到目前为止我所知,这是在C语言中(等等)的功能。尽管如此,它有什么看起来像一个伟大的答案,所以我使用grep尝试过,但grep的不知道该怎么办。我想这-P在我的箱子是指把它当作一个正则表达式PERL - 虚无缥缈。短跑E(-E)也不能工作。而且也没有-F。
只是要清楚,我想这样的事情,寻找任何输出 - 在那里,我就砍了脚本利用不管我得到的。 (IOW,我期待,当一个有效的行被重复不符合要求的输入返回任何内容。)
天翻地覆= $(回声$ 2| grep的-E/ ^ [ - +](:\\ [0-9] + |(?:??0 | [ 1-9] [0-9] *)(?:\\?[0-9] *))$ /)
如果[-z$天翻地覆];
然后
回声不是一个整数 - 没有来自grep的背
其他
回声整数。
科幻
会有人请说明如何,这是最容易做的?
坦率地说,这是一个短期的未来试验,在我看来。它应该有一个这样的标志
如果[-I字符串];
然后
回声字符串是一个有效的整数。
其他
回声字符串不是有效的整数。
科幻
感谢。
[$ VAR =〜^ - ?[0-9] + $]
I'm trying to do something common enough: Parse user input in a shell script. If the user provided a valid integer, the script does one thing, and if not valid, it does something else. Trouble is, I haven't found an easy (and reasonably elegant) way of doing this - I don't want to have to pick it apart char by char.
I know this must be easy but I don't know how. I could do it in a dozen languages, but not BASH!
In my research I found this:
And there's an answer therein that talks about regex, but so far as I know, that's a function available in C (among others). Still, it had what looked like a great answer so I tried it with grep, but grep didn't know what to do with it. I tried -P which on my box means to treat it as a PERL regexp - nada. Dash E (-E) didn't work either. And neither did -F.
Just to be clear, I'm trying something like this, looking for any output - from there, I'll hack up the script to take advantage of whatever I get. (IOW, I was expecting that a non-conforming input returns nothing while a valid line gets repeated.)
snafu=$(echo "$2" | grep -E "/^[-+]?(?:\.[0-9]+|(?:0|[1-9][0-9]*)(?:\.[0-9]*)?)$/")
if [ -z "$snafu" ] ;
then
echo "Not an integer - nothing back from the grep"
else
echo "Integer."
fi
Would someone please illustrate how this is most easily done?
Frankly, this is a short-coming of TEST, in my opinion. It should have a flag like this
if [ -I "string" ] ;
then
echo "String is a valid integer."
else
echo "String is not a valid integer."
fi
Thanks.
[[ $var =~ ^-?[0-9]+$ ]]
这篇关于BASH:字符串测试是否有效作为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!