What does sed -i option do?

UnixSedCommand LineOption

Unix Problem Overview


I'm debugging a shell script and trying to find out the task performed by the following command:

sed -i '1,+999d' /home/org_user/data.txt

I need to change this command as its failing with the following error:

illegal option sed -i

But before changing, I need to understand the BAU functioning.

Appreciate any inputs in this regard.

Unix Solutions


Solution 1 - Unix

An applicable use of this is as follows. Say you have the following file file.txt:

1, 2, 6, 7, "p" 

We want to replace "p" with 0.

sed 's/"p"/0/g' file.txt

Using the above simply prints the output into command line.

You'd think why not just redirect that text back into the file like this:

sed 's/"p"/0/g' file.txt > file.txt

Unfortunately because of the nature of redirects the above will simply produce a blank file.

Instead a temp file must be created for the output which later overwrites the original file something like this:

sed 's/"p"/0/g' file.txt > tmp.txt && mv tmp.txt file.txt

Instead of doing the long workaround above sed edit in place option with -i allows for a much simpler command:

sed -i 's/"p"/0/g' file.txt

Solution 2 - Unix

If -i option given, sed edit files in place.

> -i[SUFFIX], --in-place[=SUFFIX] > > edit files in place (makes backup if extension supplied)

from sed(1)

http://www.gnu.org/software/sed/manual/sed.html#Introduction

Solution 3 - Unix

Some implementations of sed do not support the -i option. What it does can be simulated by

sed -e '...' file > tmp
mv tmp file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAllzhereView Question on Stackoverflow
Solution 1 - UnixPhilip KirkbrideView Answer on Stackoverflow
Solution 2 - UnixfalsetruView Answer on Stackoverflow
Solution 3 - UnixchorobaView Answer on Stackoverflow