Delete lines before and after matching the specified tags in SED

Must be removed before and after the matching template in the tag

< mds:insert> 
    < attributeValues>
        < AttrNames
            < Item Value="MyContact_c"/>
        < /AttrNames>
    < /attributeValues>
< /mds:insert>

Using

sed -i -n '/MyContact_c/{s/.*//;x;d;};x;p;${x;p;}' $file

deletes only the line before and after the matching pattern, you must delete all the contents in the mds: insert tag ... Any pointers will be useful.

+3
source share
3 answers

This is not sed, but here is one for ex, using the snippet that you posted as the contents of the file for $file:

kitsune:~$ printf '%s\n' 'set ic
1;/="MyContact_c"/<|?<mds:insert?+;/<\/mds:insert>/-d
%p' | ex -s $file

Conclusion:

<mds:insert>
</mds:insert>

This will print the rest of the file after deleting the first instance of the section. If you want this to be done for all instances, the command line will look like this:

'set ic
g/="MyContact_c"/<|?<mds:insert?+;/<\/mds:insert>/-d
%p'

for script, , . , , , , , .

, - Vim vi, , .. ex IMHO.

Edit

C Shell , , C. :

kitsune:~% printf '%s\n%s\n%s\n' 'set ic' '1;/="MyContact_c"/<|?<mds:insert?+;/<\/mds:insert>/-d' '%p' | ex -s $file

.

: C, , .

0

sed:

sed -e ':a' -e '/ mds:insert/!{p;d;}' -e 'N;/\/mds:insert/{/MyContact_c/!p;d;};ba' filename

EDIT:

sed - . :

sed -e '/ mds:insert/!{p;d;}' filename

, , .

0

Here's how to do it: awk

awk '{a[NR]=$0} /MyContact_b/ {f=NR} END {for (i=1;i<=NR;i++) if (i+2<f || i-2>f || !f) print a[i]}' file
< mds:insert>
< /mds:insert>

It skips two lines before and two after patternif it is found.

0
source

All Articles