Using sed to match a pattern and deleting from the line to the end of the file

后端 未结 5 1261
感动是毒
感动是毒 2021-01-01 10:59

I\'m trying to match a pattern from piped input and/or a file, and then remove from the matched lines to the end of the file, inclusive. I\'ve looked everywhere, but can\'t

相关标签:
5条回答
  • 2021-01-01 11:29

    Here's a regular expression that I think will do what you want it to: ^(?:(?!Files:).)+|\s*-----THIS STUFF IS USELESS-----.+ Make sure to set the dotall flag.

    Demo+explanation: http://regex101.com/r/xF2fN5

    You only need to run this one expression.

    0 讨论(0)
  • 2021-01-01 11:38

    why not

     sed '/^-----THIS STUFF IS USELESS-----$/,$d' file
    

    In a range expression like you have used, ',$' will specify "to the end of the file"

    1 is first line in file, 
    $ is last line in file.
    

    output

    Files:
     somefiles.tar.gz 1 2 3
     somefiles.tar.gz 1 2 3
    


    With GNU sed, you can do

    sed '/^-----THIS STUFF IS USELESS-----$/Q' file
    

    where Q is similar to q quit command, but doesn't print the matching line

    0 讨论(0)
  • 2021-01-01 11:49

    Dirty utility knife grep version:

    cat your_output.txt | grep -B 99999999 "THIS STUFF IS USELESS" | grep -v "THIS STUFF IS USELESS"
    
    0 讨论(0)
  • 2021-01-01 11:55

    Instead of trying to figure out how to express what what you don't want, just print what you DO want:

    awk -v RS= '/Files:/' file
    

    EDIT: Given your modified input:

    awk '/^Files:$/{f=1} f; /^$/{f=0}' file
    

    or:

    awk '/^Files:$/{f=1} f; /^-----THIS STUFF IS USELESS-----$/{f=0}' file
    

    if you prefer.

    You can also use either of these:

    awk '/^Files:$/,/^-----THIS STUFF IS USELESS-----$/' file
    sed '/^Files:$/,/^-----THIS STUFF IS USELESS-----$/' file
    

    but they are hard to extend later.

    0 讨论(0)
  • 2021-01-01 11:56
    sed -e '/^-----THIS STUFF IS USELESS-----$/,$ d'
    
    0 讨论(0)
提交回复
热议问题