Confused about sed syntax
The sed examples I know are mostly in the form:
sed s/text/newtext/ file.txt
However, I see that:
sed -i '1i prepend this' file.txt
works, producing the same result as:
sed -i '1i\prepend this' file.txt
Why does the man pages talks about i \, when i alone also works?
Why are the options within the string? Why aren't they as a flag to the command. I imagine something like:
sed <options like in place, insert> "string" filename
But when I find something like:
sed <options like in place> "insert string" filename
I wonder why aren't the insert and string separated? --3dcaddy (talk) 19:24, 12 December 2015 (UTC)
- Your examples of the i command don't work in standard sed. They work in GNU sed, which is what you're probably using, and maybe some other seds. GNU sed lets you play fast and loose with the syntax, and stick text on the same line as an a, c, or i command, because it makes it easier to do a one-line command like yours. In POSIX, the a, c, and i commands must be followed by a \ and then a newline. sed is ancient, and its syntax is extremely picky and terse. It was designed for use on teletypes in the computer labs of yore. You would be expected to be familiar with the documentation. So, you would know that all sed commands are one letter, and that \ is used in Unix for line continuation, so you would know to use \ to tell sed that your text is on the following line. The man pages for sed and a lot of other utilities are not good places to learn how to use them. They're more intended for quick reference when you already know how to use the program. For learning sed, I suggest these:
- And there's the sed article, which also has some more links. --71.119.131.184 (talk) 21:31, 12 December 2015 (UTC)
- The syntax requiring multiple lines may make more sense if you consider that it was derived from ed, where the insertion commands a and i were the way you'd switch into text-entry mode. Having done so, you would often type in many lines of text at a time, until you needed to go back and edit something. (Remember, this is in a teletype-style environment.) So, similarly, the i command in sed allows you to enter many lines:
sed '1i\
One Ring to Rule them All\
One Ring to Find them\
One Ring to Bring them All\
And in the Darkness Bind them\
' file.txt
- If you're writing something like that, it looks better without the i cluttering up the first line of the insertion. --76.69.45.64 (talk) 04:02, 13 December 2015 (UTC)