0

次の形式のファイルがあります。

Preamble

---------------------
Section 1
...
---------------------

---------------------
Section 2
...
---------------------

---------------------
Section 3
...
---------------------

Afterwords

そして、結果が次のようになるように、セパレーターで各セクションを抽出したいと思います。

ファイル0:

Section 1
...

ファイル1:

Section 2
...

ファイル2:

Section 3
...

...

これを行う簡単な方法はありますか?ありがとう。

4

4 に答える 4

2

[更新] chomp を使用すると$_、これがさらに短くなります。

これはそれを行う必要があります:

入力レコードセパレーターが 21-のシーケンスである場合、これは次の方法で簡単perl -neです。

perl -ne 'BEGIN{ $/=("-"x21)."\n"; $i=0; } 
  do { open F, ">file".($i++); 
       chomp;
       print F; 
       close F; 
  } if /^Section/' yourfile.txt

動作し、ファイルを作成する必要がありますfile0.. fileN.

説明

おそらく、スタンドアロンの Perl スクリプトとして説明する方が簡単でしょうか?

$/=("-"x21)."\n"; # Set the input-record-separator to "-" x 21 times
my $i = 0;        # output file number

open IN, "<yourfile.txt" or die "$!";

while (<IN>) {  # Each "record" will be available as $_ 
  do { open F, ">file".($i++); 
       chomp;     # remove the trailing "---..."
       print F;   # write the record to the file
       close F;   #
  } if /^Section/  # do all this only it this is a Section
}

ここではPerl のawk系譜が役に立ちましたので、比較のためにawkバージョンを示しましょう。

awk 'BEGIN{RS="\n-+\n";i=0} 
  /Section/ {chomp; print > "file_"(i++)".txt" 
}' yourfile.txt

バージョンに比べて悪くはありませんがperl、実際には短くなっています。$/Perl の は の変数RSですawk。ここでは awk が優勢です:RS正規表現かもしれません!

于 2012-12-13T09:14:27.730 に答える
1

これがあなたが探しているものです:

awk '/^-{21}$/ { f++; next } f%2!=0 { print > "file" (f-1)/2 ".txt" }' file

結果:

内容file0.txt

Section 1
...

内容file1.txt

Section 2
...

内容file2.txt

Section 3
...

ご覧のとおり、上記のファイル名には「ゼロ」のインデックスが付けられています。ファイル名'one'にインデックスを付けたい場合は、単にに変更(f-1)/2して(f+1)/2ください。HTH。

于 2012-12-13T16:02:38.450 に答える
1

シェルでもできます:

#!/bin/bash

i=0
while read line ; do

 #If the line contain "Section " followed by a 
 #digit the next lines have to be printed
 echo "$line"|egrep -q "Section [0-9]+"
 if [ $? -eq 0 ] ; then
  toprint=true
  i=$(($i + 1))
  touch file$i
 fi

 #If the line contain "--------------------"  
 #the next lines doesn't have to be printed
 echo "$line"|egrep -q "[-]{20}"
 if [ $? -eq 0 ] ; then
  toprint=false
 fi

 #Print the line if needed
 if $toprint ; then
  echo $line >> file$i
 fi

done < sections.txt
于 2012-12-13T09:36:51.147 に答える
0

ファイルの形式を考えると、次の 1 つのオプションがあります。

use strict;
use warnings;

my $fh;
my $sep = '-' x 21;

while (<>) {
    if (/^Section\s+(\d+)/) {
        open $fh, '>', 'file' . ( $1 - 1 ) . '.txt' or die $!;
    }

    print $fh $_ if defined $fh and !/^$sep/;
}

データ上で、以下を含むものを作成file0.txt .. file2.txtしますfile0.txt:

Section 1
...
于 2012-12-13T15:23:44.793 に答える