2010-08-03 67 views
3

我有一個文本文件,

一個部分複製到一個新的文件

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


,我需要從標記證明二份(直到標記兩個端)到一個新的文件,使用bash 。

!--- Marker two --! 
eeee 
ffff 

成爲一個單獨的文件。

回答

8

AWK

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

慶典

#!/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 
1

,你可以用 'sed的' 做什麼經典案例:

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

唯一的問題是如果第一個標記在數據中出現多次。模式匹配節的開始和下一節的開始;大括號內的命令刪除第二部分開頭的行,並打印所有其他行。

也可以處理多個這樣的模式來分離用「w」命令文件(稍微不同的匹配方案 - 但能夠適於在一個以上如果需要的話):

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

等等

相關問題