是否有更好的方式来双重转义(或转义两次)用户输入在BASH比调用printf两次? [英] Is there a better way to double escape (or escape twice) user input in BASH than calling printf twice?

查看:343
本文介绍了是否有更好的方式来双重转义(或转义两次)用户输入在BASH比调用printf两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此脚本将从用户读取旧值和新值,然后使用sed在文件中查找和替换它们。例如,如果我输入了T< T> z和B> B> z,它将在文件中寻找T \ T \ z,并替换为B\ B\ ž。它的作品,但我一直在努力使这更简洁。

This script will read an old and a new value from the user and then use sed to find and replace them in a file. For example if I entered TTz and BBz it would look for T\T\z in the file and replace with B\B\z. It works but I've been trying to make this more concise.

我不需要中间变量$ ESC_OLD_PW和$ ESC_NEW_PW。是否有更多的 明智的 方式来做到这一点?

I don't have any need for the intermediate variables $ESC_OLD_PW and $ESC_NEW_PW. Is there a more sensible way to do this?

    #!/bin/bash
    read -sp "Old:" OLD_PW && echo
    read -sp "New:" NEW_PW && echo

    # Add escape characters to what user entered
    printf -v ESC_OLD_PW "%q" "${OLD_PW}"
    printf -v ESC_NEW_PW "%q" "${NEW_PW}"

    # Escape again for the sed evaluation.
    printf -v ESC_ESC_OLD_PW "%q" "${ESC_OLD_PW}"
    printf -v ESC_ESC_NEW_PW "%q" "${ESC_NEW_PW}"

    sed -i -e s/"${ESC_ESC_OLD_PW}"/"${ESC_ESC_NEW_PW}"/g $1

以下:

    ~$ OLD_PW="T*T*z"
    ~$ printf "%q" $OLD_PW | xargs printf "%q"
    printf: %q: invalid conversion specification
    ~$



And I've tried many variations on piping things into printf... Any suggestions?

推荐答案

中间无变量:

sed -i -e "s/$(printf '%q' $(printf '%q' $OLD_PW))/$(printf '%q' $(printf '%q' $NEW_PW))/g" $1

这篇关于是否有更好的方式来双重转义(或转义两次)用户输入在BASH比调用printf两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆