我正在努力将 sed
的引用作为函数的参数传回。
举个例子
join() { sep="$1"; shift; echo -n "$1"; shift; printf "$sep%s" "$@"; }
index_of() {
local value="${1}"
shift
local array=("${@}")
for (( i = 0; i < ${#array[@]}; i++ )); do
if [ "${array[$i]}" = $value ]; then
echo $i
fi
done
}
array=('foo' 'bar' 'baz')
regex=$(join '\|' "${array[@]}")
echo 'baz' 'bar' 'foo' | sed "s/\(${regex}\)/[$(index_of "\1" ${array[@]})] \1/g"
我期待它输出 baz [2] bar [1] foo [0]
,但它返回 baz [] bar [] foo []
因为这会将 '\1'
作为值传递,而不是 sed
的匹配。
如何将实际匹配项作为参数传递?
最佳答案
正如我所说,您需要重新考虑您的计划。
这里是一个重写:
index_of() {
local value=$1 arrayname=$2 # we're passing the array by name
local tmp="${arrayname}[@]" # and then jumping through a hoop
local array=("${!tmp}") # to get the values
# this is just a different way of iterating through the array
local i=0
for elem in "${array[@]}"; do
if [[ $elem == $value ]]; then
echo $i
break # save some time when a match is found
fi
((i++))
done
}
array=('foo' 'bar' 'baz')
# here's the big change: have to call the function in the same context
# as iterating through the words.
# in other words, call the shell function from the same shell
for word in baz bar foo; do
printf "%s [%d] " "$word" $(index_of "$word" "array")
done
还有一个更高效的join
函数
join() {
local IFS="$1"
shift
echo "$*"
}
关于linux - 使用 sed 的反向引用作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29255779/