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.
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.
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With