如何在 Bash 中测试字典序小于或等于的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21294867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test strings for lexicographic less than or equal in Bash?
提问by tskuzzy
In Bash, is there a simple way to test if one string is lexicographically less than or equal to another?
在 Bash 中,是否有一种简单的方法来测试一个字符串在字典上是否小于或等于另一个字符串?
I know you can do:
我知道你可以这样做:
if [[ "a" < "b" ]]
for testing strict inequality, or
用于测试严格的不等式,或
if [[ 1 -le 1 ]]
for numbers. But -le
doesn't seem to work with strings, and using <=
gives a syntax error.
对于数字。但-le
似乎不适用于字符串,并且使用<=
会出现语法错误。
回答by Gordon Davisson
Just negate the greater than test:
只需否定大于测试:
if [[ ! "a" > "b" ]]
回答by anubhava
You need to use ||
with an additional condition instead of <=
:
您需要使用||
附加条件而不是<=
:
[[ "$a" < "$b" || "$a" == "$b" ]]
回答by WinEunuuchs2Unix
You can flip the comparison and sign around and test negatively:
您可以翻转比较并签名并进行否定测试:
$ a="abc"
$ b="abc"
$ if ! [[ "$b" > "$a" ]] ; then echo "a <= b" ; fi
a <= b
If you want collating sequence of "A" then "a" then "B"... use:
如果你想整理“A”然后“a”然后“B”的序列......使用:
shopt -s nocaseglob
回答by t0r0X
If you can use the Bash syntax, see the answers from @anubhava and @gordon-davisson. With POSIX syntax you have two options (note the necessary backslashes!):
如果您可以使用 Bash 语法,请参阅 @anubhava 和 @gordon-davisson 的答案。使用 POSIX 语法,您有两个选项(注意必要的反斜杠!):
using the -o
operator (OR):
使用-o
运算符 (OR):
[ "$a" \< "$b" -o "$a" = "$b" ] && echo "'$a' LTE '$b'" || echo "'$a' GT '$b'"
or using negation:
或使用否定:
[ ! "$a" \> "$b" ] && echo "'$a' LTE '$b'" || echo "'$a' GT '$b'"
I prefer the first variant, because imho it's more readable.
我更喜欢第一个变体,因为恕我直言,它更具可读性。