Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does sed -i option do?

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.

like image 668
Allzhere Avatar asked Aug 30 '13 07:08

Allzhere


People also ask

How do you use sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

Should I use sed or awk?

Conclusion: Use sed for very simple text parsing. Anything beyond that, awk is better. In fact, you can ditch sed altogether and just use awk. Since their functions overlap and awk can do more, just use awk.

What does sed do in bash?

sed is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement. The s,%,$,g part of the command line is the sed command to execute. The s stands for substitute, the , characters are delimiters (other characters can be used; / , : and @ are popular).

What is P option in sed?

In sed, p prints the addressed line(s), while P prints only the first part (up to a newline character \n ) of the addressed line. If you have only one line in the buffer, p and P are the same thing, but logically p should be used.


1 Answers

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 
like image 72
Philip Kirkbride Avatar answered Sep 23 '22 23:09

Philip Kirkbride