Home > front end >  How to change a file's content using sed with multiple quotes and spaces in it?
How to change a file's content using sed with multiple quotes and spaces in it?

Time:10-07

So I'm working on a Ubuntu Docker image and have to replace a settng in a file using sed.

I'd like to change #$nrconf{restart} = 'i' into $nrconf{restart} = 'a'

The way I understand it is that I have to escape ', $, {, }. I then tried it using this sed command (tried with and without escaping #)

sed -i 's/#\$nrconf\{restart\}[[:space:]]=[[:space:]]\'i\'/\$nrconf\{restart\}[[:space:]]=[[:space:]]\'a\'/g' /etc/needrestart/needrestart.conf

But when I test the command it expects an input and when I run the command in a Docker image I get this error Syntax error: Unterminated quoted string

What am I missing? I think escaping the quotes is correct, I don't get it

CodePudding user response:

Using sed

$ sed -E "s/^#($nrconf[^']*')[^']*/\1a/" input_file
$nrconf{restart} = 'a'

CodePudding user response:

With GNU sed could you please try following code. Using sed's capability of capturing groups where it uses regex ^#(\$nrconf[^}]*} = '"'"')[^'"'"'](.*)$ and then while substituting them it uses \1a\2 to get the expected output as per shown samples.

sed -E 's/^#(\$nrconf[^}]*} = '"'"')[^'"'"'](.*)$/\1a\2/' Input_file

CodePudding user response:

This might work for you (GNU sed):

sed '/#$nrconf{restart} = '\''i'\''/c nrconf{restart} = '\''a'\'''

When dealing with tricky regexps, a sound best practice is to surround any sed commands by single quotes, this reduces shell side effects down to one.

The one side effect remaining is what to do when the regexp includes single quotes?

The simple solution is replace all single quotes (inside of the sed commands) by '\'', this closes the current send command and drops into the underlying shell. The shell uses \' to represent a single quote and the final ' allows the remaining sed commands to be quoted.

N.B. This solution uses the c command which replaces the matching line completely. Also the solution could be shortened (and now you know why):

sed '/#$nrconf{restart} = '\''i'\''/c $nrconf{restart} = '"'a'"

or

sed '/#$nrconf{restart} = '\''i'\''/c $nrconf{restart} = '\'a\'
  • Related