regex - sed -e to display only a block of text - can you explain the command? -
regex - sed -e to display only a block of text - can you explain the command? -
i've managed build sed command accomplish need help of colleagues nobody can explain why works!
can advise please?
my text file is:
this test configuratoin first test dn: cn=configuration line1 can line2 can linex can end of story no end of story
my sed command is:
sed -e '/./{h;$!d;}' -e 'x;/dn: cn=configuration/!d'
the output is:
dn: cn=configuration line1 can line2 can linex can
i understand h = hold (append newline, append contents of pattern space, hold space) , {} allows multiple commands.
any guidance, much appreciated.
first analysis
first, expressions given sed
through -e
alternative can grouped single script*, so
sed -e '/./{h;$!d;}' -e 'x;/dn: cn=configuration/!d' my_file
is equivalent to
sed -e '/./{h;$!d;};x;/dn: cn=configuration/!d' my_file
now let's split see how works:
sed -e '/./{ # non-empty lines (containing @ to the lowest degree 1 char): { h; # happend line hold space, $!d; # , if not lastly line of file, delete it. # go next line of input. }; # } x; # reach point empty lines , lastly line of file # “x” command swaps hold , pattern spaces /dn: cn=configuration/!d # if pattern space not contain # “dn: cn=configuration”, delete it. ' my_file
!
means: “perform command on lines not matching preceding pattern”.
*at to the lowest degree gnu sed, don't know other versions.
more details/./{h;$!d;}
non-empty lines, save them in sed
hold space, , delete pattern space (except lastly line). go next line of input (the d
command ends treatment of current line).
x
when meet empty line, lastly line of file (empty or not), swap hold space (which contains saved non-empty lines) , current pattern space. after swapping, saved lines in pattern space, , hold space empty.
/dn: cn=configuration/!d
@ pattern space (i.e. saved lines): contain, on line, string dn: cn=configuration
? if no, delete pattern space (and both hold , pattern spaces blank). if yes, nothing, print pattern space (i.e. saved lines). loop line of input.
putting of together, have: each stanza containing no empty lines, save hold space; on empty line (or @ end of file), content hold space, , search dn: cn=configuration
string inside. if stanza not contain string, delete it; else, print (default behaviour of sed
).
so script prints stanzas containing string dn: cn=configuration
. remove blank line @ top of output , forcefulness string on first line of stanza with:
sed -e '/./{h;$!d;};x;s/^\n//;/^dn: cn=configuration/!d' my_file # changes: ^^^^^^^ ^
(s/^\n//
remove first empty line in pattern space, ^
anchor string @ origin of stanza).
don't hesitate inquire more details in comments if remains unclear.
regex bash sed edit ksh
Comments
Post a Comment