linux - 使用 sed 的反向引用作为函数参数

标签 linux bash sed

我正在努力将 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/

相关文章:

Linux 命令在 shell 上运行良好但在脚本中运行不正常

python - 如何确保脚本由特定版本的python执行?

c++ - 我可以使用较新的 gcc/clang 来定位较旧的 linux 吗? C++

linux - 在 shell 脚本中运行的非 shell 命令

swift - 使用 awk/sed 获取 swift 函数的返回类型

linux - 在小数点前插入逗号恰好 1 个空格

macos - OSX 上的 LANG 和 sed

php - Apache mod-rewrite 不接受查询字符串中的双引号

bash - 如何从 Bash 脚本检查程序是否存在?

django - powershell中的bash导出命令