[英]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
A
和B
正確,但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.