Tuesday, May 18, 2010

SED-insert text at the top and bottom of a file using sed?

SkyHi @ Tuesday, May 18, 2010
From the command line use
(Note that these must be completed on separate lines.)
This will insert on the first line of the file.

sed '1i\
your text goes here' file_name > new_filename

This will append on the last line of the file.
sed '$a\
your text goes here' file_name > new_filename

Note also that with sed you have to direct the output and rename the file back. So 'mv new_filename file_name' when you are done with these commands.


Problem 1:

I get the error:
sed: command garbled: 1iEXEC PR_DbConfigStart 'test.txt', '10', 'DESCRIPTION'

when I try this.

Here is the script im using

sed -e "1i\
EXEC PR_DbConfigStart 'some text', '10', 'DESCRIPTION' " < $FILENAME >$TMPFILENAME

You need a second backslash:
sed -e "1i\\

Problem 2:

What about for the statement that appends data to the end of the file?

sed "$a\\

I get the error message:

sed: command garbled: \

If I remove the second backslash:

sed "$a\

I get this error message:

sed: command garbled: PR_DbConfigEnd test2.txt

#! /usr/bin/ksh
sed -e "\$a\\
exit 0

Inside single quotes, what you see is what you get. No character has any special meaning inside single quotes. So variables won't expand. A string like:
will just be $a. The shell will not try to substitute the value of a variable called a. So in the line:
sed '$a\
we get exactly what we ask for. Inside single quotes, even the backslash is just another character. (And, btw, this means that there is no way to get a single quote inside single quotes...so 'you can't do that' won't work and there is no way to fix it with backslashes.)

When you want to use a variable inside single quotes, it won't work:
'something $var something'
isn't going to do it. So we must break that single quoted string into two single quoted string and put the variable between them:
'something '$var' something'
is actually good enough, but most folks will add {} whenever a variable touches non-blanks, not just other letters:
'something '${var}' something'

And finally, if the value of var has a string of blanks, we would need to protect them, so we would need single quotes around the variable:
'something '"${var}"' something'
And this get us to the syntax that you used. Your first single quoted string started on one line and finished on the next but otherwise it's pretty much what we have here.