2011-11-08 32 views
0
空行

我有一個文本文件,它看起來像:新的文本文件基於

6789 Here is a bunch of text 

4565 More text...................................................... 
.....etc 

我需要拉出第一個字(數字),並創建一個新的文件包含所有以下文本的製作第一個字的文件名直到空行,然後重複創建許多文本文件。

回答

2

awk的線可以做到這一點:

awk 'BEGIN{RS=""} {fn=$1;gsub(/^[0-9]+\s/,"");print $0 > (fn".txt")}' yourFile 

測試

kent$ l 
total 0 
(no file in current dir) 

kent$ echo "6789 Here is a bunch of text 

4565 More text...................................................... 
.....etc"|awk 'BEGIN{RS=""} {fn=$1;gsub(/^[0-9]+\s/,"");print $0 > (fn".txt")}' 

kent$ ls 
4565.txt 6789.txt 

and, the contents are: 

kent$ head *.txt 
==> 4565.txt <== 
More text...................................................... 
.....etc 

==> 6789.txt <== 
Here is a bunch of text 
+0

令人印象深刻的使用awk'的'。 – ObscureRobot

0

awk和斯普利特會做(的一部分)的作業:如果你真的需要根據在文件開頭的號碼每個文件進行重命名

$ awk '{print $1} < foo | split -p '^$' 

,那麼你可能會想解決這個在Perl或Python中的問題。