I would re-think this a bit. The proper use of sed is to use the /address/ section to match the lines you want, then the command(s) following it (especially, but not limited to, 's///') to modify them.
So first figure out what makes the line unique and easy to target. It doesn't have to be the string you want to change. If, for example, it's the "exit 0", then use that for the address. sed would thus only modify lines containing it. You can use regex patterns, line numbers, line ranges, and more. Whatever works.
The commands following the address then target and modify the part of the matched lines that you want to change. Multiple commands can be grouped and/or nested with '{ ; }'. Here, I use a second, nested /address/ string to further filter the line:
Code:
#The input file. We want to change only the first line.#
$ cat infile.txt
[ ${NETWORKING} = "no" ] && exit 0
[ "${NETWORKING}" = "no" ] && exit 0
[ ${NETWORKING} = "no" ] && exit 1
[ Another unimportant ${NETWORKING} string ]
Code:
$ sed '/exit 0/ { /[^"]${N.*G}[^"]/ s/${N.*G}/"&"/ }' infile.txt
[ "${NETWORKING}" = "no" ] && exit 0
[ "${NETWORKING}" = "no" ] && exit 0
[ ${NETWORKING} = "no" ] && exit 1
[ Another unimportant ${NETWORKING} string ]
It first finds any line containing 'exit 0', then checks those lines for an unquoted '${N.*G}' string. If it finds one, it adds quotes around it. Notice how I simplified the regex down to (close to) the minimal phrase needed to get the match. It helps keep the code short and readable.
Actually, though, the following is slightly simpler. No nested commands are needed:
Code:
$ sed '/exit 0/ s|"\?\(${N.*G}\)"\?|"\1"|' infile.txt
[ "${NETWORKING}" = "no" ] && exit 0
[ "${NETWORKING}" = "no" ] && exit 0
[ ${NETWORKING} = "no" ] && exit 1
[ Another unimportant ${NETWORKING} string ]
or
$ sed -r '/exit 0/ s|"?(\$\{N.*G\})"?|"\1"|' infile.txt
[ "${NETWORKING}" = "no" ] && exit 0
[ "${NETWORKING}" = "no" ] && exit 0
[ ${NETWORKING} = "no" ] && exit 1
[ Another unimportant ${NETWORKING} string ]
We don't actually have to check for quotes, when we can simply replace them with themselves if they already exist.
Unfortunately, with this particular input, we either have to use sed in basic regex mode and escape the extended regex characters, or use extended regex mode (-r) and escape the special characters in the string. So to avoid the "picket fence" effect and help readability, I also changed 's///' to 's|||'. (Any ascii character not found in the pattern or the input string can be used as the delimiter.)
And finally, I found the sed FAQ to be very useful for learning how to use the full power of the command... although it is a bit out of date now:
http://sed.sourceforge.net/sedfaq.html