简体   繁体   中英

bash, sed, awk: extracting lines within a range

How can I get sed to extract the lines between two patterns, write that data to a file, and then extract the lines between the next range and write that text to another file? For example given the following input:

pattern_a
line1
line2
line3
pattern_b
pattern_a
line4
line5
line6
pattern_b

I want line1 line2 and line3 to appear in one file and line4 line5 and line6 to appear in another file. I can't see a way of doing this without using a loop and maintaining some state between iterations of the loop where the state tells you where sed must start start search to looking for the start pattern (pattern_a) again.

For example, in bash-like psuedocode:

while not done
  if [[ first ]]; then
    sed -n -e '/pattern_a/,/pattern_b/p' > $filename
  else
    sed -n -e '$linenumber,/pattern_b/p' > $filename
  fi
  linenumber = last_matched_line
  filename = new_filename

Is there a nifty way of doing this using sed? Or would awk be better?

How about this:

awk '/pattern_a/{f=1;c+=1;next}/pattern_b/{f=0;next}f{print > "outfile_"c}' input_file

This will create a outfile_x for every range.

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