I came across this command in a project I am working on:
sed -i '/regex/,$d' file
I don't understand how the ,$d
part works. If I omit any part of ,$d
I get errors. In my tests it looks like it replaces the matching line and anything after it with nothing. Example:
File with contents:
first line
second line regex
third line
fourth line
Comes out as after running that command:
first line
I couldn't find any documentation in the man page that explains this, though I could have easily missed it. The man page is hard for me to parse...
This is example was tested with GNU Sed v 4.2.2
.
It means that sed will read the next line and start processing it. Your test script doesn't do what you think. It matches the empty lines and applies the delete command to them.
Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. Output : linux is great os.
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.
In the help for sed you will find that -e flag stands for: -e script, --expression=script add the script to the commands to be executed. But you are not the first to be confused after encountering -e .
This is not a replacement command; the sed
substitute or replace command looks like s/from/to/
.
The general form of a sed
script is a sequence of commands - typically a single letter, but some of them take arguments, like the s
command above - with an optional address expression before each. You are looking at a d
(delete line) command preceded by the address expression /regex/,$
The address range specifies lines from the first regex match through to the end of the file ($
in this context specifies the last line) and the action d
deletes the specified lines.
Although many people only ever encounter simple sed
scripts which use just the s
command, this behavior will be described in any basic introduction to sed
, as well as in the man page.
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