Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the 'd' command in the sed utility

Tags:

sed

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.

like image 885
Just a learner Avatar asked Nov 22 '11 12:11

Just a learner


2 Answers

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.

like image 167
Michael J. Barber Avatar answered Sep 19 '22 21:09

Michael J. Barber


a) You can combine multiple commands for one pattern with curly braces:

sed '/^$/{d;p;p}' test.txt

aaaaaaaaaaaaaa
bbbbbbbbbbbbb
ccccccccc
ddd
eeeeeee

The command d is only applied to empty lines here: '/^$/d;p;p'. Else the line is printed 2 additional times. To bind the 'p'-command to the pattern, you have to build curly braces. Then the p-command is as well skipped, but because of the skipping to next cycle, not because it doesn't match.

b) Useless use of cat. (already shown)

like image 40
user unknown Avatar answered Sep 23 '22 21:09

user unknown