3

I have two files: junk.txt and lines.txt

$>cat junk.txt
This is a junk text
$>cat lines.txt
Line1
Line2
Line3
Line4

When I fire the following sed script

 sed -i -e  "/Line3/r junk.txt" -e "s///" lines.txt

I get this output:

Line1
Line2

This is a junk text
Line4

As you can see, Line3 is no more there. Ok, the /Line3/r junk.txt part finds the text in the lines.txt matching Line3 and appends the contents of the junk.txt. But why does the s/// command remove exactly the matched line?

To be honest, that's the behavior I need but I want to know why it behaves like that.

1 Answer 1

5

When the editing command s is invoked with an empty regular expression, it reuses the expression most recently used. In this case, it reuses Line3 from the matching of it earlier. This applies to // (empty regular expressions) in both the s command and in address ranges.

Your command could also be written, without this feature, as

sed -i -e '/Line3/r junk.txt' -e 's/Line3//' lines.txt

The Line3 text is removed because it is replaced by nothing.

You would sometimes see this in constructs like

/expression/ {
    s//replacement/
    # other code here
}

The POSIX specification for sed formulates this as

If an RE is empty (that is, no pattern is specified) sed shall behave as if the last RE used in the last command applied (either as an address or as part of a substitute command) was specified.

4
  • This was also my interpretation, i.e. similar to vim, but I couldn't find any official mention of this in the sed manual. Do you know if it's documented anywhere?
    – Sparhawk
    Jun 20, 2019 at 12:09
  • Ahhh, I see now. So "s/text-to-replace/replace-with". If we omit the replace-with, it's going to replace it with nothing and if we go further and omit the text-to-replace it uses the recent expression to match, which in this case is Line3. That makes sense. Jun 20, 2019 at 12:10
  • 1
    @Sparhawk vi, sed, and ed are all the same editor, and vim is vi. Jun 20, 2019 at 12:11
  • 1
    @Sparhawk Check section 4.3.
    – Kusalananda
    Jun 20, 2019 at 12:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .