[求助]如何按规律把一个文件拆分成若干个文件?sed?awk?

sh/bash/dash/ksh/zsh等Shell脚本
回复
头像
ywzhaifei
帖子: 18
注册时间: 2008-02-18 12:16

[求助]如何按规律把一个文件拆分成若干个文件?sed?awk?

#1

帖子 ywzhaifei » 2008-12-21 13:50

代码: 全选

Sun 21%cat tmp.txt
* Whetting Your Appetite
* Using the Python Interpreter
  * Invoking the Interpreter
    * Argument Passing
    * Interactive Mode
  * The Interpreter and Its Environment
    * Error Handling
    * Executable Python Scripts
    * Source Code Encoding
    * The Interactive Startup File
* An Informal Introduction to Python
  * Using Python as a Calculator
    * Numbers
    * Strings
    * Unicode Strings
    * Lists
  * First Steps Towards Programming
我想把tmp.txt文件按标题分成各个文件。
例如

代码: 全选

cat 1.txt
* Whetting Your Appetite

代码: 全选

cat 2.txt
* Using the Python Interpreter
  * Invoking the Interpreter
    * Argument Passing
    * Interactive Mode
  * The Interpreter and Its Environment
    * Error Handling
    * Executable Python Scripts
    * Source Code Encoding
    * The Interactive Startup File

代码: 全选

cat 3.txt
* An Informal Introduction to Python
  * Using Python as a Calculator
    * Numbers
    * Strings
    * Unicode Strings
    * Lists
  * First Steps Towards Programming

sed '/*/,/*/!d' tmp.txt 是最大匹配的,不行
那要如何实现。
我的一个超级麻烦的方法 :em06 是先tmp.txt编序号,sed '=',再把主标题的序号提取出来,i=2,j=11,再用sed -n "$i,$jp" .
有没好的方法?? :em01
aerofox
帖子: 1453
注册时间: 2008-05-24 8:30

Re: [求助]如何按规律把一个文件拆分成若干个文件?sed?awk?

#2

帖子 aerofox » 2008-12-21 14:28

csplit
头像
xiooli
帖子: 6956
注册时间: 2007-11-19 21:51
来自: 成都
联系:

Re: [求助]如何按规律把一个文件拆分成若干个文件?sed?awk?

#3

帖子 xiooli » 2008-12-21 14:36

代码: 全选

cat tmp.txt|grep "^\*"|while read line;do 
    echo "$line">"${line/\*/}"
    sed -n "/$line/,/^\*/p" tmp.txt|grep -v "^\*">>"${line/\*/}"
done
有点丑。。 :em03
头像
ywzhaifei
帖子: 18
注册时间: 2008-02-18 12:16

Re: [求助]如何按规律把一个文件拆分成若干个文件?sed?awk?

#4

帖子 ywzhaifei » 2008-12-21 15:22

en,it works!
太好了,比我的那个好多了。。
thanks very much.
aBiNg
帖子: 1331
注册时间: 2006-07-09 12:22
来自: 南京

Re: [求助]如何按规律把一个文件拆分成若干个文件?sed?awk?

#5

帖子 aBiNg » 2008-12-22 13:13

代码: 全选

awk 'BEGIN{c=0;e=".txt"}{if($0~/^*/)c++;print $0>c e}' foo
头像
xiooli
帖子: 6956
注册时间: 2007-11-19 21:51
来自: 成都
联系:

Re: [求助]如何按规律把一个文件拆分成若干个文件?sed?awk?

#6

帖子 xiooli » 2008-12-22 13:35

aBiNg 写了:

代码: 全选

awk 'BEGIN{c=0;e=".txt"}{if($0~/^*/)c++;print $0>c e}' foo
这个生猛 :em11 不过好像应该将if($0~/^*/)写成if($0~/^\*/)才行。
aerofox
帖子: 1453
注册时间: 2008-05-24 8:30

Re: [求助]如何按规律把一个文件拆分成若干个文件?sed?awk?

#7

帖子 aerofox » 2008-12-23 12:38

用脚本编程固然没有错,但完成这个任务最直接的还是csplit。
回复