美文网首页
Linux string操作

Linux string操作

作者: halfempty | 来源:发表于2021-12-01 10:22 被阅读0次

    1. 长度

    ${#string}

    myString="abc123abc456"
    
    echo ${#myString}               # 12
    

    expr length $string

    myString="abc123abc456"
    
    expr length ${myString}         # 12
    

    2. 索引

    expr index $string $substring

    myString="abc123abc456"
    
    expr index "$myString" "123"        # 4
    

    3. 子集

    ${string:position}

    ${string:position:length}

    myString="abc123abc456"             
    
    echo ${myString:0}                  # abc123abc456
    echo ${myString:4}                  # 23abc456
    
    echo ${myString:3:3}                # 123
    

    4. 左右清除

    ${string#substring}, 从左往右, 移除最小匹配

    ${string##substring}, 从左往右, 移除最大匹配

    ${string%substring}, 从右往左, 移除最小匹配

    ${string%%substring}, 右右往左, 移除最大匹配

    myString="abc123abc456"
    
    echo ${myString#a*c}                # 123abc456
    echo ${myString##a*c}               # 456
    
    echo ${myString%c*}                 # abc123ab
    echo ${myString%%c*}                # ab
    

    5. 替换

    ${string/substring/replacement}, 只替换第一个匹配子集

    ${string//substring/replacement}, 替换全部匹配子集

    myString="abc123abc456"
    
    echo ${myString/abc/XYZ}            # XYZ123abc456
    echo ${myString//abc/XYZ}           # XYZ123XYZ456
    

    相关文章

      网友评论

          本文标题:Linux string操作

          本文链接:https://www.haomeiwen.com/subject/jshsxrtx.html