1

I was looking at this solution: Using sed to edit lines in a file with a variable and tried to apply it to my situation, but I have only recently discovered sed and haven't got the hang of it yet.

If I have a file located /tmp/mary.txt and it looks like this:

Mary had a little lamb
with fleece as white as
snow. Everywhere that
Mary went, the lamb was
sure to go.

I want to replace a line of text in this file, specifically:

Mary had a little lamb -> Mary had 2 little lambs

I used this:

sed -i 's/*.had a little lamb.*/Mary had $(nproc) little lambs/' /etc/mary.txt

I am using -i for inplace and s/ for substitute and it throws error:

sed: 1: "mary.txt": extra characters at the end of g command

The other thing I am trying to do, is replace the word "lamb" on the first line with the result of echo $PATH

sed -i 's/*.had a little lamb.*/ Mary had a little '$(echo $PATH)'/' /etc/mary.txt

This throws the same error as above. I know these are two different scenarios, but can it be shown to me what I did wrong, so I can use this in future.

4

Use double quotes to have the var evaluated properly:

$ var=43
$ sed "s/.*had a little lamb.*/Mary had $var little lambs/" file
Mary had 43 little lambs
with fleece as white as
snow. Everywhere that
Mary went, the lamb was
sure to go.

See Jacob Minshall's answer regarding the .* instead of *.. I had written the sed command from scratch, so I did not notice the error in the original code.

  • +1 for the answer and +100 for your avatar. És realment molt trist. – terdon Feb 28 '14 at 15:53
  • Excellent. I didn't understand the .* and *. were causing the issue. Thank you. And the double quotes I know understand. I tried it out a couple of times doing different things. – Danijel-James W Feb 28 '14 at 15:56
  • @terdon ho és :( But we are lucky to have a lifetime to keep listening Paco's art. – fedorqui Feb 28 '14 at 15:59
2

I think it is because you have *. at the beginning, but you want to have .*

The . means any character, while the * means zero or more of the preceding character, which there isn't one of

  • ah yes, and @fedorqui definitely got it, double quotes as well – Jacob Minshall Feb 28 '14 at 15:41
  • Thank you for explaining what .* actually means. I have had trouble understanding that part. – Danijel-James W Feb 28 '14 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.