条件sed多次替换

时间:2017-04-29 10:13:05

标签: bash sed

我试图创建一个bash(或sh)脚本,用read询问一个或多个输入,然后从默认文件生成一个配置文件,当它们存在时用{{替换自定义的默认值1}}。

这可以通过多次调用sed来完成,但我想知道是否可以通过一个命令实现这一点,如下所示。

你知道这是否可能,我怎么做?或者这不值得这样做,最好多次调用sed -i

sed -i

config-sample.yml的一个例子是:

echo "config install title? "
read title
if [ -z "$title" ]; then
    echo "title from config-sample.yml will be used to generate config.local.yml."
    #exit 1
fi

echo "config install url (required, start with http:// or https:// )? "
read url
if [ -z "$url" ]; then
    echo "url localhost will be used to generate config.local.yml."
    #exit 1
fi

sed \
    [ -n "$title" ] && -e "s/title:.*/title: \"${title}\" /" \
    [ -n "$url" ]   && -e "s/url:.*/url: \"${url}\" /" \
    config-sample.yml > config.yml

1 个答案:

答案 0 :(得分:0)

如果你有gnu gettext,我建议改用envsubst,这里有一个例子:

while : ; do
    [[ -z $title ]] && read -rp "config install title? " title
    # keep asking for the title until the user gives it
    [[ -z $title ]] && continue
    read -rp "config install url? " url
    case "$url" in
        # keep asking for the url
        "" )
            continue
            ;;
        # accept urls without protocol and use https by default
        [!http]*)
            url="https://${url}"
            ;;
    esac
    break
done
# export the vars you want to substitute in the template
export title url
envsubst '${title} ${url}' < "config-sample.yml" > "config.yml"

主要的是您导出所需的变量$title $url,然后将它们作为envsubst的选项提供,并且它将替换${title}的任何匹配项,$title中的${url}$url和/或config-sample.yml,然后输出会重定向到新文件config.yml