0

Background

I would like to take the following string from /etc/default/hostapd and add a certain value after the =:

#DAEMON_CONF="" -> DAEMON_CONF="/etc/hostapd/hostapd.conf"

Test

un_comment_and_add_value() {
       file="$1"
       given_str="$2" ##DAEMON_CONF=""
       value="$3" # /etc/hostapd/hostapd.conf
                  #dont know where to put this in the 'sed' cmd

       sed -i "/$given_str/s/^#//g" "$file"
}

un_comment_and_add_value "/etc/default/hostapd" "#DAEMON_CONF=\"\"" "/etc/default/hostapd"
don_crissti
  • 82,805

4 Answers4

1

For given example, try

sed -i "/^$given_str/{s/.//; s|.$|$value\"|}" "$file"
  • Note the use of double quotes, allows variable interpolation
  • /^$given_str/ if given string matches at start of line
    • s/.// remove the first character
    • s|.$|$value\"| replace the last character with given replacement string and a double quote

Further Reading:

Sundeep
  • 12,008
0

You may use something like this:

sed -i /etc/default/hostapd -e '/^#DAEMON_CONF=/s;^#\([^=]*\)=.*;\1='"${VALUE}"';'

  • -i edit file in place
  • /etc/default/hostapd file to edit
  • /^#DAEMON_CONF=/ filter lines starting with #DAEMON_CONF=
  • s; substitute
  • ^#\([^=]*\)=.*; substitute the whole line, but remember the variable name, the string between # and up until =, ie. DAEMON_CONF in this case
  • \1=${VALUE} substitute line by the ${remembered variable name}=${VALUE}
KamilCuk
  • 860
0

I done this by below sed command let me know for any questions

Taken input file as below

cat /etc/default/hostapd

#DAEMON_CONF=""

command:

sed -i '/#DAEMON_CONF/s/^#//g' /etc/default/hostapd ; sed -i 's/"/&\/etc\/hostapd\/hostapd.conf/1' /etc/default/hostapd 

output

DAEMON_CONF="/etc/hostapd/hostapd.conf"
0
$ cat input
#DAEMON_CONF=""
$ key=DAEMON_CONF
$ value="/etc/hostapd/hostapd.conf"

$ sed "/^$key/ { s/^#//; s%=.*%=\"$value\"%; }" input
DAEMON_CONF="/etc/hostapd/hostapd.conf"

Two things here. First, to expand the shell variables, you need to put them in double quotes, not in single quotes. Two, you need to group the substitutions so that they're both dependent on the pattern match. (Or duplicate the pattern match before each s///.) Three, since the replacement contains slashes, we'd better use some other character as separator for s, like the percent sign here.

Do note that you need to be sure that the variable value doesn't contain percent signs, then; and if you need to insert a literal $ or a backslash in the sed command, you'll need to escape them, since the shell processes them inside backslashes.

Then you also might want to consider this, too: How to ensure that string interpolated into `sed` substitution escapes all metachars

ilkkachu
  • 138,973