开发者

Copy a section into a new file

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 separ开发者_运维问答ate file.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜