user2678235
user2678235

Reputation: 23

How to double quote the passed variable using sed?

I am new to scripting. I want to add a double quotes to passed variable using sed. I have written the script file but it is not inserting the double quote. My script looks like

#!/bin/bash

essid=$1
port=$2

sed -i -e "s/\(ssid=\).*/\1$1/" \
-e "s/\(key_mgmt=\).*/\1$2/" iwlist_details.txt 

I want to replace ssid = "xyz" with ssid = "abcd"

network={
ssid="xyz"
key_mgmt=WAP
proto=WPA2
pairwise=CCMP TKIP
group=CCMP TKIP
psk="hello123"

}

when I run the script I get the following output

#./myscrip.sh abc WAP iwlist_details.txt


network={
ssid=abcd
key_mgmt=WAP
proto=WPA2
pairwise=CCMP TKIP
group=CCMP TKIP
psk="hello123"
}

How to add the double quotes around "abcd" ?

Thanks Sachin

Upvotes: 0

Views: 112

Answers (1)

choroba
choroba

Reputation: 242048

You did not use double quotes. How should sed know you want them? To use double quotes inside double quotes, backslash them:

sed -i -e "s/\(ssid=\).*/\1\"$1\"/" \
   -e "s/\(key_mgmt=\).*/\1\"$2\"/" iwlist_details.txt 

or use them inside single quotes:

sed -i -e 's/\(ssid=\).*/\1"'"$1"'"/' \
   -e 's/\(key_mgmt=\).*/\1"'"$2"'"/' iwlist_details.txt 

I am not sure which one you find more readable.

Upvotes: 1

Related Questions