Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

The command inserts a tag to the beginning of a file:

sed -i "1s/^/<?php /" file

How can I insert something to the end of each file with SED?

share|improve this question

migrated from superuser.com Sep 12 '11 at 22:28

This question came from our site for computer enthusiasts and power users.

{ cat file; echo 'END OF FILE'; } > newFile , this works also thanks to sh.*. (not sed but works and simple) –  user2362 Dec 12 '11 at 14:20

6 Answers 6

up vote 19 down vote accepted

-e "\$aTEXTTOEND" is the simplest way

share|improve this answer
Wow! You rock, this is a hit to the back. Why and how does it actually work? Some zero-width thing? –  user2362 Dec 12 '11 at 14:00
@hhh $ matches the last line (it's a normal sed address; 4aTEXTTOEND would insert after the fourth line), a is the append command, and TEXTTOEND is what to append –  Michael Mrozek Dec 12 '11 at 14:26
Escape $ as $$ in a Makefile. –  stevesliva Dec 3 '14 at 1:22

Assuming you want to put the ending php tag to the files, then

sed -i '$s/$/\n?>/' file

should do the trick

share|improve this answer

No need to use sed in that case. How about

echo "<?php" >> file
share|improve this answer
True enough, but you can guess that the OP's use case is bracketing the file with "<php " and ">", and quoting selected contents all in one go, so he probably really does want a sed fragment. –  dmckee Sep 6 '09 at 15:12
Also if you'll do this and don't want a newline, use echo -n –  Vinko Vrsalovic Sep 6 '09 at 15:15
I don't like to guess. Each time I try, I'm wrong. –  innaM Sep 6 '09 at 15:38
Another reason why the accepted answer is more useful is in the case of prepending this with sudo, which causes this variation to fail since echo is a built-in shell command rather than an executable file found in $PATH –  Tony Cesaro Oct 28 '14 at 15:33

See your original post for the all in one sed command.

find . -type f -exec sed -i -e "1s/^/<?php /" -e "\$s/\$/ ?>/" {} \;
share|improve this answer

Use sed 'append (a)' command. For example, to append two lines at the end of file:

sed -i -e '$a\
foo1 bar1\
foo2 bar2' file
share|improve this answer

In a simple way to write and make the changes in the contents at a specific line in a file . If you want to insert anything at a specific line number then below command can be used:

sed -i '2i i have started' sheikh.log

where 2i - line number 2 and i stands for inserting . If you have to insert at the last line then use $ in place of 2 . i have started - text to be inserted and sheikh.log is the filename .

We can also make the changes in the line by using the below command

sed -i '2c we have started' sheikh.log

i is changed to we .

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.