Search code examples
sed

the 'd' command in the sed utility


From the sed documentation:

d      Delete the pattern space; immediately start next cycle.

What does it mean by next cycle? My understanding is that sed will not apply the following commands after the d command and it starts to read the next line from the input stream and processes it. But it seems that this is not true. See this example:

[root@localhost ~]# cat -A test.txt
aaaaaaaaaaaaaa$
$
bbbbbbbbbbbbb$
$
$
ccccccccc$
ddd$
$
eeeeeee$
[root@localhost ~]# cat test.txt | sed '/^$/d;p;p'
aaaaaaaaaaaaaa
aaaaaaaaaaaaaa
aaaaaaaaaaaaaa
bbbbbbbbbbbbb
bbbbbbbbbbbbb
bbbbbbbbbbbbb
ccccccccc
ccccccccc
ccccccccc
ddd
ddd
ddd
eeeeeee
eeeeeee
eeeeeee
[root@localhost ~]# 

If immediately start next cycle, the p command will not have any output.

Anyone can help me to explain it please? Thanks.


Solution

  • 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. They don't appear, so the print statements don't get applied to the empty lines. The two print commands aren't connected to the pattern for the delete command, so the non-empty lines are printed three times. If you instead try

    sed '/./d;p;p' test.txt # matches all non-empty lines
    

    nothing will be printed other than the blank lines, three times each.