1

I have this string that I want to include at line 115 of a file, using sed. However, it always complains on some unknown command. I have followed other solutions in other questions, but haven't managed to solve it.

sed '115"<"img src="\.\/index_files\/Logo\.png" width="200" height="160" align="right" border="0">"' index.html > test.html

Thanks!

3

Because " is not a sed command. As it says in the error message, though not very clearly.

The address 115 has to be followed by a sed command, probably i

  • Then get rid of some of the "s. The ones around the < and after the >
  • Then don't escape the /s, they don't need escaping.
  • Then don't escape anything as i command just takes text.

This left we with: sed '115 i <img src="./index_files/Logo.png" width="200" height="160" align="right" border="0">'

2

User richard describes very well what's wrong with your sed command, and also gives the correct editing script to perform the action you're attempting.

I'm giving an alternative approach which will work in a number of different cases:

The sed command r will insert the contents of a file at the current position in the data stream.

Your sed command line could be written

$ sed '115r /dev/stdin' index.html <data.in

which would have the same effect as sed '115r data.in' index.html... if the data that you wanted to insert after line 115 was stored in the file data.in.

/dev/stdin is a special file that contains whatever is sent through the standard input.

You could also do (with shells supporting "here-strings"):

$ sed '115r /dev/stdin' index.html <<<"my string of stuff"

or

$ sed '115r /dev/stdin' index.html <<<"$myvariableofwonder"

This also works as expected with piping from other commands, obviously:

$ sed -n '1,10p' myfile | sed '115r /dev/stdin' index.html

This will transplant lines 1 to 10 of myfile into index.html at line 115.

  • 2
    I like this. However be aware that some systems, Microsoft's Windows is an example do not have /dev/stdin. (for some tools such as gnu awk, it will interpret the /dev/stdin it self so will work on these legacy systems). – ctrl-alt-delor Jan 19 '17 at 16:32
  • 1
    @richard Good point. Does work in Microsoft's new Linux environment, and in Cygwin, but not in MinGW (no /dev). – Kusalananda Jan 19 '17 at 16:44
  • 1
    Oh good they got /dev/stdin working in gnu/cygwin now. It did not work when I used it about 10 years ago. – ctrl-alt-delor Jan 19 '17 at 16:51
  • What about MacOS X, BSD and other Unixes do they have /dev/stdin? – ctrl-alt-delor Jan 19 '17 at 16:54
  • 1
    Thanks for this answer. Very helpful indeed! However, I marked the other as accepted, since it was solving exactly the question as you said. – Santi Mar 6 '17 at 10:11

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.