Arvind Sridharan Arvind Sridharan - 1 month ago 5
Linux Question

How do I run the sed command with input and output as the same file?

I'm trying to do use the sed command in a shell script where I want to remove lines that read

STARTremoveThisComment
and lines that read
removeThisCommentEND
.

I'm able to do it when I copy it to a new file using

sed 's/STARTremoveThisComment//' > test


But how do I do this by using the same file as input and output?

Answer

sed -i (or the extended version, --in-place) will automate the process normally done with less advanced implementations, that of sending output to temporary file, then renaming that back to the original.

The -i is for in-place editing, and you can also provide a backup suffix for keeping a copy of the original:

sed -i.bak fileToChange
sed --in-place=.bak fileToChange

Both of those will keep the original file in fileToChange.bak.

Keep in mind that in-place editing may not be available in all sed implementations but it is in GNU sed which should be available on all variants of Linux, as per your tags.

If you're using a more primitive implementation, you can use something like:

sed 'whatever' oldfile >newfile ; mv newfile oldfile

though some more error checking would be nice.