2013-10-29 70 views
4

,如果我有一個文件test.txt:AWK桑達拆分文件

example 1 content 2013-3-8: 
hello java 
example 2 content 2013-4-9: 
hello c 

我怎麼可以用AWK或sed將test.txt的單獨的兩個文件

test1的

hello java 

test2的

hello c 

我使用下面的命令:

awk '/example/{i++}{print > "test"i}' test.txt 

,但它仍將是第一行(例如XXX),我可以在AWK一些片段添加到打印刪除的第一線?

回答

6

你幾乎有它:

awk '/^example/ { i++; next } { print >"test"i}' 

next使得awk跳過語句的其餘部分。

2

您可以使用getline跳過第一行。以下應得到所需要的輸出:

awk '/example/{getline; i++}{print > "test"i}' test.txt 
0

你可以嘗試這樣的:

awk 'BEGIN {i=0; j=0} /example/{i++; j=0} (j != 0){print > "test"i} {j++}' test.txt 
0
sed -n " 
/example 1/ {N;s/^.*\n// 
    w test1.txt 
    } 
/example 2/ {N;s/^.*\n// 
    w test2.txt 
    }" test.txt 

如果定義部分(限定尺寸或標記),有可能是擺在每個文件

1

有些怪異更多的文本之間的分隔符這樣做與sed的方式:

sh <<< $(sed '/example/{N;s/\n//;s/example \([0-9]*\).*:\(.*\)/echo "\2" >> test\1;/}' input) 
1

這可能適合你(GNU sed):

sed -ne '2~4w test1.txt' -e '4~4w test2.txt' test0.txt 
0

要完成Alok Singhal的迴應:如果您在Linux上達到「太多打開的文件」限制,您必須關閉文件。

awk '/^example/ {close("test" i); i++; next } { print >"test" i}'