簡體   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