Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of ",$d" in replacement part of sed command

Tags:

sed

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.

like image 713
lps Avatar asked Sep 20 '16 17:09

lps


People also ask

What is $d in sed?

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.

Which sed command is used for replacement?

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.

How do you replace words in 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.

What is E flag in sed?

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 .


1 Answers

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.

like image 132
tripleee Avatar answered Oct 20 '22 05:10

tripleee