bash – 条件表达式如何比较字符串?

前端之家收集整理的这篇文章主要介绍了bash – 条件表达式如何比较字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#!/usr/bin/env bash
echo 'Using conditional expression:'
[[ ' ' < '0' ]] && echo ok || echo not ok
[[ ' a' < '0a' ]] && echo ok || echo not ok
echo 'Using test:'
[ ' ' \< '0' ] && echo ok || echo not ok
[ ' a' \< '0a' ] && echo ok || echo not ok

输出是:

Using conditional expression:
ok
not ok
Using test:
ok
ok

bash –version:GNU bash,版本4.2.45(1)-release(x86_64-pc-linux-gnu)

uname -a:Linux linuxmint 3.8.0-19-generic

Bash手册说:

When used with [[,the < and > operators sort lexicographically using the current locale. The test command sorts using ASCII ordering.

这归结为分别使用strcoll(3)或strcmp(3).

使用以下程序(strcoll_strcmp.c)来测试:

#include <stdio.h>
#include <string.h>
#include <locale.h>

int main(int argc,char **argv)
{
    setlocale(LC_ALL,"");

    if (argc != 3) {
        fprintf(stderr,"Usage: %s str1 str2\n",argv[0]);
        return 1;
    }

    printf("strcoll('%s','%s'): %d\n",argv[1],argv[2],strcoll(argv[1],argv[2]));
    printf("strcmp('%s',strcmp(argv[1],argv[2]));

    return 0;
}

注意区别:

$LC_ALL=C ./strcoll_strcmp ' a' '0a'
strcoll(' a','0a'): -16
strcmp(' a','0a'): -16

$LC_ALL=en_US.UTF-8 ./strcoll_strcmp ' a' '0a'
strcoll(' a','0a'): 10
strcmp(' a','0a'): -16

究竟为什么这些比较,我不确定.这必须归功于一些英语词典排序规则.我认为确切的规则在ISO 14651 Method for comparing character strings and description of the common template tailorable ordering和附带的模板表中描述. Glibc在libc / localedata / locales下的源代码树中包含此数据.

原文链接:https://www.f2er.com/bash/384351.html

猜你在找的Bash相关文章