简体   繁体   English

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

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

The following index_of function doesn't work for all cases:以下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"

Here is the output:这是 output:

A: 9
B: 2
C: -1

The A and B is correct, but the C is incorrect. AB正确,但C不正确。

The C should be 0 instead of -1 . C应该是0而不是-1

What's wrong in the index_of function and how to fix the C index? 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"

result结果

A: 9
B: 2
C: 0

When using parameter expansion in the pattern part of constructs like ${param/pattern/repl} , quote the parameter expansion to remove the special meaning of any shell pattern metacharacters that may exist in the parameter.${param/pattern/repl}等结构的pattern部分使用参数扩展时,请引用参数扩展以删除参数中可能存在的任何 shell 模式元字符的特殊含义。

Here's a slightly different implementation of your index_of function.这是您的index_of function 的稍微不同的实现。 In case the length of the second argument is zero, the index shall be zero.如果第二个参数的长度为零,则索引应为零。 At the end, a return value is provided to indicate success or failure.最后,提供一个返回值来指示成功或失败。 "$2" is quoted in ${1/"$2"*/} so it is treated literally, not as a shell pattern. "$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: output:

9
2
0

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

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