以正则表达式 search/replace 字符串作为参数的 sed 包装函数

Wrapper function for sed that takes regex search/replace string as parameters

我正在尝试创建一个 sed 包装器,它首先检查文件是否存在,如果存在,运行 使用指定的参数。例如:

sed_wrapper 's/replace this/with this/g' test_file.txt

如果正则表达式中没有空格,我的尝试工作正常,但一旦添加空格,它就会中断。 总而言之,如何将包含空格和引号的函数参数作为函数内的命令 运行?

脚本:

#!/bin/bash
# ./test_script.sh

sed_wrapper() {
    ALL_PARAMETERS=($@)
    ALL_PARAMETERS_LENGTH=${#ALL_PARAMETERS[@]}
    PARAMETER_FILE=${ALL_PARAMETERS[$ALL_PARAMETERS_LENGTH_-1]}
    PARAMETER_REGEX=${ALL_PARAMETERS[@]:0:$ALL_PARAMETERS_LENGTH-1}

    echo "ALL_PARAMETERS: $ALL_PARAMETERS"
    echo "-------------------------------"
    if [ -f "$PARAMETER_FILE" ] ; then
        sed $PARAMETER_REGEX $PARAMETER_FILE
    fi
}

sed_wrapper 's/#REPLACETHIS/[=12=]--->simple_example/g' test_file.txt
echo "************************************************************"
sed_wrapper 's/#REPLACETHIS/[=12=]--->complex example/g' test_file.txt
echo "************************************************************"
sed_wrapper "'s/#REPLACETHIS/[=12=]--->quotation_example/g'" test_file.txt

test_file.txt的内容:

#REPLACETHIS

运行ning 的输出./test_script.sh:

ALL_PARAMETERS: s/#REPLACETHIS/[=14=]--->simple_example/g test_file.txt
-------------------------------
#REPLACETHIS--->simple_example
************************************************************
ALL_PARAMETERS: s/#REPLACETHIS/[=14=]--->complex example/g test_file.txt
-------------------------------
sed: -e expression #1, char 28: unterminated `s' command
************************************************************
ALL_PARAMETERS: 's/#REPLACETHIS/[=14=]--->quotation_example/g' test_file.txt
-------------------------------
sed: -e expression #1, char 1: unknown command: `''

运行ning 的预期输出./test_script.sh:

ALL_PARAMETERS: s/#REPLACETHIS/[=15=]--->simple_example/g test_file.txt
-------------------------------
#REPLACETHIS--->simple_example
************************************************************
ALL_PARAMETERS: s/#REPLACETHIS/[=15=]--->complex example/g test_file.txt
-------------------------------
#REPLACETHIS--->complex example
************************************************************
ALL_PARAMETERS: 's/#REPLACETHIS/[=15=]--->quotation_example/g' test_file.txt
-------------------------------
#REPLACETHIS--->quotation_example

当运行最后的sed命令,可以使用原来的参数:

使用带引号的 $@。它将确保正确引用所有参数。

sed "$@"

而不是:

sed $PARAMETER_REGEX $PARAMETER_FILE

bash 中有更简单的构造来执行创建 'silent_sed' 的任务。 (为简单起见,从函数中删除了日志语句)

sed_wrapper() {
    local PARAMETER_FILE=${@:#$}
    if [ -f "$PARAMETER_FILE" ] ; then
        sed "$@"
    fi
}