0

I wish to use sed in ubuntu to replace a row in a file file.txt.

my row starts with a certain pattern foo followed by any number of any characters. I wish to replace this with foo='x'. I was trying to use the following command from bash:

sed -i 's/^foo*/foo='x'/g' file.txt

Obviously the ' symbol brakes the string transferred to sed. Moreover, the regular expressions don't sim to work for me when I remove the problematic symbol. I simply replace only the pattern foo and not the whole row.

For example the original file.txt:

foo='bla'

The requested result file.txt:

foo='SomethingElse'

I tried a number of variables such as: sed -i 's/\^foo\*/foo=\'x\'/g' file.txt to no avail. I could not find information on the subject online though I am sure this is not the first time someone encountered this problem.

How do I use ' in the target (or the pattern I am searching for that matter)? And what is up with the regex in this approach?

havakok
  • 1,185
  • 2
  • 13
  • 45

1 Answers1

2

Using sed

sed "/foo/s/='.*'/='1234'/g" file
foo='1234'

This search for foo, then replace =' with ='1234 on that line.

When you have ' int your text, change start and stop of sed to "

Another variation using back reference and -E

sed -E "s/(foo=').*/\11234'/g" file
foo='1234'

If you like to use single quote, you have to get out of sed with single quote and then escape the single quote and then a new single quote to get in to sed like this messy solution:

sed '/foo/s/='\''.*/='\''1234'\''/g' file

or hex code it:

sed '/foo/s/=\x27.*\x27/=\x271234\x27/g' file
Jotne
  • 40,548
  • 12
  • 51
  • 55