[英]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.