removing lines between two patterns (not inclusive) with sed

后端 未结 6 473
遇见更好的自我
遇见更好的自我 2020-12-09 20:08

Ok

I know that this is trivial question but: How can i remove lines from files that are between two known patterns/words:

pattern1
garba

相关标签:
6条回答
  • 2020-12-09 20:34
    awk '/pattern1/{g=1;next}/pattern2/{g=0;next}g' file
    
    0 讨论(0)
  • 2020-12-09 20:40

    This sed code will work as well:

    sed '/PATTERN1/,/PATTERN2/d' FILE
    
    0 讨论(0)
  • 2020-12-09 20:44
    sed -n '/pattern1/{p; :a; N; /pattern2/!ba; s/.*\n//}; p' inputfile
    

    Explanation:

    /pattern1/{         # if pattern1 is found
        p               # print it
        :a              # loop
            N           # and accumulate lines
        /pattern2/!ba   # until pattern2 is found
        s/.*\n//        # delete the part before pattern2
    }
    p                   # print the line (it's either pattern2 or it's outside the block)
    

    Edit:

    Some versions of sed have to be spoon-fed:

    sed -n -e '/pattern1/{' -e 'p' -e ':a' -e 'N' -e '/pattern2/!ba' -e 's/.*\n//' -e '}' -e 'p' inputfile
    
    0 讨论(0)
  • 2020-12-09 20:55

    This might work for you:

    sed '/pattern1/,/pattern2/{//!d}' file
    
    0 讨论(0)
  • 2020-12-09 21:00

    This is easily done with awk:

    BEGIN { doPrint = 1; }
    /pattern1/ { doPrint = 0; print $0; }
    /pattern2/ { doPrint = 1; }
    { if (doPrint) print $0; }
    

    I've found the sed info is fairly easy reading, with many examples. Same thing for awk.

    0 讨论(0)
  • 2020-12-09 21:00

    You may also use the Unix text editor ed:

    echo '
    pattern1
    garbage
    pattern2
    ' > test.txt
    
    cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s test.txt &>/dev/null
      H
      /pattern1/+1,/pattern2/-1d
      wq
    EOF
    

    For more information see: Editing files with the ed text editor from scripts

    0 讨论(0)
提交回复
热议问题