Issue
I'm trying to understand a shell command : sed -n 'p;n'
with this you will be able to print on line of two, I'm trying to understand how it command works (n;p
), why is it having this behaviour.
For example if I'm doing p;n;n
, it will select one line of three, but p;p;n
it will print twice the first line, hide the second one, print twice the third one etc., why it isn't printing the first and second line, and hide the third one ?
I hope I was a bit clear, it's hard to explain my problem, if anyone can help me.
Solution
sed -n 'p;n'
-n
suppresses all output that isn't explicitly printed.
'p;n'
is the sed script to run on each input line. The semicolon is a separator between two commands, p
and n
.
p
prints the current line, without moving to the next line.
n
moves to the next line without printing anything.
Once these two commands have been run on the current line, sed moves on to the next line, and then runs the script again on this new line. This script will keep running until there are no more input lines. The effect of the script is to keep printing, then skipping lines.
p;n;n
This is mostly the same script, but it skips two lines instead of one.
p;p;n
This is mostly the same script, but it prints the line twice before skipping it.
why it isn't printing the first and second line, and hide the third one ?
Because p
doesn't advance sed forward a line, only n
(or reaching the end of the script) does that.
(It might be helpful to note that sed -n 'p'
prints every line without skipping any, sed -n 'p;p;p'
prints every line three times, and sed -n 'p;n;p'
is equivalent to sed -n 'p'
.)
Answered By - Ollin Boer Bohan Answer Checked By - Marie Seifert (WPSolving Admin)