使用sed命令在Bash Scripting中使用引号和\进行引号

时间:2013-01-19 22:47:01

标签: bash variables raspberry-pi raspbian

我正在编写一个bash脚本来帮助我更快地设置rpi的网络接口。它现在大部分都已完成,并使用sed来改变/ etc / network / interfaces文件的不同部分,具体取决于网络接口的设置方式。我的问题是我插入引号,我不想要它们,如果我删除引号,我插入包含要插入的数据的变量作为变量名的字符串,而不是插入它们作为它们的值。< / p>

我的代码如下(虽然我已将其删除)

#!/bin/bash
ANS=''
ssid=''
psk=''
file='/etc/network/interfaces'
ip=''
netmask=''
broadcast=''
gateway=''
function static {
    echo 'Will now set up Static IP'
    echo 'What IP address do you want to assign this Device?'
    echo -e '> \c'
    read ip
    echo 'What is your Networks Netmask/Subnet?'
    echo -e '> \c'
    read netmask
        echo 'What is your Networks Broadcast Address?'
        echo -e '> \c'
        read broadcast
        echo 'What is the address of your Networks Gateway?'
        echo -e '> \c'
        read gateway
    echo 'You entered the following information about your Network'
    echo ''
    echo 'Address: ' $ip
    echo 'Netmask: ' $netmask
    echo 'Broadcast: ' $broadcast
    echo 'Gateway: ' $gateway
    echo 'Is this information correct? (y/n)'
    echo -e '> \c'
        read ANS
        if [ $ANS = 'y' ]; then
        sed -i "s/^iface eth0 inet dhcp.*\$/iface eth0 inet static/" $file
        sed -i "s/^#    address.*\$/    address \"$ip\"/" $file
        sed -i "s/^#    netmask.*\$/    netmask \"$netmask\"/" $file
        sed -i "s/^#    broadcast.*\$/  broadcast \"$broadcast\"/" $file
        sed -i "s/^#    gateway.*\$/    gateway \"$gateway\"/" $file
        echo 'Static IP address has now been set up'
        start
    else
        static
    fi
}

问题在于这些行

        sed -i "s/^#    address.*\$/    address \"$ip\"/" $file
        sed -i "s/^#    netmask.*\$/    netmask \"$netmask\"/" $file
        sed -i "s/^#    broadcast.*\$/  broadcast \"$broadcast\"/" $file
        sed -i "s/^#    gateway.*\$/    gateway \"$gateway\"/" $file

插入address "(var_address)"。正如我所说,我可以插入address $address。但不是,正如我所愿,address (var_address)。有人可以解释如何使用/和\与sed命令中的“和”一起使我可以解决问题。因为你可能已经猜到了一些新的bash所以任何帮助都是值得赞赏的。

2 个答案:

答案 0 :(得分:2)

虽然bash不会尝试解析没有标准变量,例如$/,但你可以简单地说:

sed "
    /^iface $iface/,/^$/{
        /address/s/^.*$/\taddress $ip/;
        /netmask/s/^.*$/\tnetmask $netmask/;
        /broadcast/s/^.*$/\tbroadcast $broadcast/;
        /gateway/s/^.*$/\tgateway $gateway/;

    }" -i $file

Nota:此修改仅有1段$iface:第一个sed行:/^iface $iface/,/^$/{ ... }分隔一个命令块,该命令块只能从匹配{{{1}的行执行1}}到空行(或文件末尾)。

要使用bash中的IP地址播放,请查看https://serverfault.com/a/461831/142978

答案 1 :(得分:1)

如果我理解了正确的要求,这应该有效:

sed -i "s/^#    address.*\$/    address $ip/" $file
sed -i "s/^#    netmask.*\$/    netmask $netmask/" $file
sed -i "s/^#    broadcast.*\$/  broadcast $broadcast/" $file
sed -i "s/^#    gateway.*\$/    gateway $gateway/" $file