sed -n "/regexp/p" will print only lines that match regexp and no other. This seems exactly equivalent to what grep does. The only use case I see to use this construct instead of grep is if you're already doing something inside of sed and piping to another program would be unwieldly.
Can anyone think of other reasons why they would use this construct over grep?
The command sed -n '/re/p' (or sed '/re/!d', without using -n to suppress the default output at the end of each cycle) is identical to grep -e 're', and both can be traced back to the ed editor's g/re/p command ("globally match re and print"); using sed and grep in a basic way like this is like running a g command over a text in ed.
If all you want to do is to print the lines that matches a particular regular expression, use grep. This is what grep does. It's its most basic task. It would make your shell code cleaner and easier to understand and to maintain if you used grep rather than sed for this task.
Use /re/p in sed if it's part of some longer sed editing script. Don't pipe grep into sed or the other way around, unless you have some really particular and quirky requirements.
Note that the /re/ in the sed command is an address. It addresses all the lines that matches the particular regular expression. With /re/p, it prints those lines. In other words, /re/ is the address for the p command.
Addresses can be line numbers too, or a range described by two line numbers, two regular expressions, or a combination thereof. So you could, for example, use sed -n '5,/re/p' to print all lines from line 5 to whatever line matches re. The grep utility doesn't have this ability, which sed inherited from the ed editor.
In summary: grep is the more appropriate tool for just extracting the lines matching a particular regular expression. To extract lines matching more complex criteria (e.g. within some range), use sed or awk.
Notice the size:
$ ls -lh /bin/grep /bin/sed
-rwxr-xr-x 1 root root 207K Apr 29 2016 /bin/grep
-rwxr-xr-x 1 root root 72K Feb 11 2016 /bin/sed
$
grep uses more memory than sed
And the execution time (real):
$ time date | grep Apr
Fri Apr 17 13:31:11 PDT 2020
real 0m0.035s
user 0m0.000s
sys 0m0.016s
$ time date | sed -n '/Apr/p'
Fri Apr 17 13:31:29 PDT 2020
real 0m0.028s
user 0m0.000s
sys 0m0.016s
$
See how sed is a little bit faster?
In an embedded environment which is resource constrained, that may matter.
sed is 44096 bytes while grep is 41512 bytes. - Kusalananda
sedciould use start and end addresses and permit a lot of things: try this:seq 1 200000 | sed -ne '/^100000$/,/^15/{/\(34\).*\1/p}'then think about! - F. Hauri - Give Up GitHub