繁体   English   中英

无法索引 bash 中的“#[hello]”

[英]Can't index of the "#[hello]" in bash

以下index_of function 不适用于所有情况:

#!/bin/bash

index_of() {
    local string="$1"
    local search_string="$2"
    
    local prefix=${string/${search_string}*/}
    
    local index=${#prefix}
     
    if [[ index -eq ${#string} ]];
    then
        index=-1
    fi
    
    printf "%s" "$index"
}

a='#[hello] world'

b=$(index_of "$a" "world")
echo "A: $b"

b=$(index_of "$a" "hello")
echo "B: $b"

b=$(index_of "$a" "#[hello]")
echo "C: $b"

这是 output:

A: 9
B: 2
C: -1

AB正确,但C不正确。

C应该是0而不是-1

function 的index_of有什么问题以及如何修复C索引?

#!/bin/bash

index_of() {
    local string="$1"
    local search_string="$2"

    local prefix=${string/${search_string}*/}

    local index=${#prefix}

    if [[ $index -eq ${#string} ]];
    then
        index=-1
    fi

    printf "%s" "$index"
}

a='#[hello] world'

b=$(index_of "$a" "world")
echo "A: $b"

b=$(index_of "$a" "hello")
echo "B: $b"

b=$(index_of "$a" "\#\[hello\]")
echo "C: $b"

结果

A: 9
B: 2
C: 0

${param/pattern/repl}等结构的pattern部分使用参数扩展时,请引用参数扩展以删除参数中可能存在的任何 shell 模式元字符的特殊含义。

这是您的index_of function 的稍微不同的实现。 如果第二个参数的长度为零,则索引应为零。 最后,提供一个返回值来指示成功或失败。 "$2"${1/"$2"*/}中被引用,因此它被视为字面意思,而不是 shell 模式。

#! /bin/bash -

index_of () {
    local idx pfx

    pfx=${1/"$2"*/}
    idx=$((${#1} == ${#pfx} ? -!!${#2} : ${#pfx}))

    printf '%s\n' "$idx"
    return "$((idx < 0))"
}

for str in world hello '#[hello]'; do
    index_of '#[hello] world' "$str"
done

output:

9
2
0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM