Sed '$! N; $! D '

I know that

cat foo | sed '$!N;$!D'

will print the last two lines of the foo file, but I don't understand why.

I read the man page and know that N joins the next line to the current processed line, etc. - but can anyone explain in "good English", which corresponds to the working order, what is happening here, step by step?

thank!

+3
source share
2 answers

Here is what the script looks like when run through sedsed(by Aurelio Jargas):

$ echo -e 'a\nb\nc\nd' | sed '$!N;$!D'        PATT:^a$
PATT:^a$
COMM:$ !N
PATT:^a\Nb$
COMM:$ !D
PATT:^b$
COMM:$ !N
PATT:^b\Nc$
COMM:$ !D
PATT:^c$
COMM:$ !N
PATT:^c\Nd$
COMM:$ !D
PATT:^c\Nd$
c
d

, ( "HOLD" ), . "PATT" , "COMM" , . "\n" . , "^" "$" .

!N , !D script, . , $! , , script , ( -n ).

: sedsed , , ^ Python 3. ( hasn ) .

+4

$!N;$!D - sed, : $!N $!D.

$!N , ($ !) N, , , , ( " " ). , sed .

$!D , , . D sed .

, :

For every line up to but not including the last {
    Read the next line and append it to the pattern space
    If still not at the last line
        Delete the first line in the pattern space
}
Print the pattern space
+1

Source: https://habr.com/ru/post/1788188/


All Articles