简体   繁体   中英

removing lines between two patterns (not inclusive) with sed

Ok

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

pattern1
garbage
pattern2

to obtain:

pattern1
pattern2

And does anyone known good(simple written!) resources for studying sed?? With many clear examples?

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

这可能对你有用:

sed '/pattern1/,/pattern2/{//!d}' file

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 .

awk '/pattern1/{g=1;next}/pattern2/{g=0;next}g' file

这个sed代码也可以运行:

sed '/PATTERN1/,/PATTERN2/d' FILE

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

for me "sed '\/PATTERN1\/,\/PATTERN2\/d' FILE" is working (between PATTERN1 and last occurrence of PATTERN2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM