tags:

views:

35

answers:

2

I have a text file,

!--- Marker one --!
aaaa
bbbb
cccc
dddd
!--- Marker two --!
eeee
ffff
!--- Marker three --!
gggg
hhhh
iiii


And I need to copy from Marker two (till the end of Marker two) into a new file, using Bash.

!--- Marker two --!
eeee
ffff

Becomes a separate file.

+2  A: 

awk

$ awk '/Marker two/{f=1;print;next}f&&/Marker/{exit}f' file
!--- Marker two --!
eeee
ffff

bash

#!/bin/bash

flag=0
while read -r line
do
  case "$line" in
     *"Marker two"*)
         flag=1; echo $line;continue
  esac
  case "$flag $line" in
   "1 "*"Marker"* ) exit;;
   "1"* ) echo $line;;
  esac
done <"file"

sed

$ sed  -n '/Marker two/,/Marker three/{/Marker three/!p}' file
!--- Marker two --!
eeee
ffff
ghostdog74
+1  A: 

Classic case of what you can do with 'sed':

sed -n '/^!--- Marker two --!/,/^!--- Marker three --!/{
        /^!--- Marker three --!/d;p;}' \
    infile > outfile

The only gotcha is if the first marker appears more than once in the data. The patterns match the start of section and start of the next section; the commands within the braces delete the line for the start of the second section, and print all the other lines.

You can also process multiple such patterns to separate files using the 'w' command (slightly different matching scheme - but can be adapted to the one above if need be):

sed -n -e '/!--- Marker one --!/,/!--- Marker two --!/w file1' \
       -e '/!--- Marker three --!/,/!--- Marker four --!/w file2' infile

Etc.

Jonathan Leffler