SED delete specific lines between two patterns?

时光毁灭记忆、已成空白 提交于 2020-01-01 03:49:10

问题


I am trying to filter an *.ics file using sed. The *.ics file looks like this:

[...]

BEGIN:VEVENT
UID:0xfoo
SUMMARY:foo
DTSTART:20131212T090000
DTEND:20131212T100000
SEQUENCE:0
DTSTAMP:20131212T100000
LOCATION:foo
CATEGORIES:foo
DESCRIPTION:foo
CLASS:PUBLIC
END:VEVENT

[...]

I want to delete lines starting e.g. with UID or SEQUENCE, but only if they are between BEGIN:VEVENT and END:VEVENT

I tried to delete these lines with:

sed '/^BEGIN:VEVENT/,/^END:VEVENT/ /^UID/d'

But it will only return an error saying something like unknown command '/'

How is it possible to delete these lines?

Thanks!


回答1:


try this line:

 sed '/^BEGIN:VEVENT/,/^END:VEVENT/{/^\(UID\|SEQUENCE\)/d}' file



回答2:


sed is an excellent tool for simple substitutions on a single line, for anything else just use awk:

awk '
/BEGIN:VEVENT/ { inBlock = 1 }
inBlock {
    if ( /END:VEVENT/ ) {
        inBlock = 0
    }
    else if ( /^(UID|SEQUENCE)/ ) {
        next
    }
}
{ print }
' file

Pseudo-code explanation (inBlock is a boolean variable, and line is just an imaginary string variable):

WHILE read line from file DO

    IF ( line contains the regexp "BEGIN:VEVENT" ) THEN
        inBlock = TRUE

    ENDIF

    IF ( inBlock == TRUE ) THEN

        IF ( line contains the regexp "END:VEVENT" ) THEN
            inBlock = FALSE

        ELSIF ( line starts with the regexp "UID" or "SEQUENCE" ) THEN
            do no further processing on this line

        ENDIF

    ENDIF

    print the current line

ENDWHILE



回答3:


Another awk

awk '/^BEGIN:VEVENT/,/^END:VEVENT/ {if ($0~/^UID|^SEQUENCE/) next}1' file

If line starts with UID or SEQUENCE in the block section from BEGIN:VEVENT to END:VEVENT, just skip the line



来源:https://stackoverflow.com/questions/19233578/sed-delete-specific-lines-between-two-patterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!