2011-12-23 9 views
2

からスプリットhtmlファイル私はこのようなコメントをhtmlファイルを持っている(一部は入れ子にすることができます)のAwk - コメント

<!-- Begin foo.html --> 
<p>some html code</p> 

    <!-- Begin foo2.html --> 
    <p>some html code</p> 
    <!-- End foo2.html --> 

<!-- End foo.html --> 

<!-- Begin bar.html --> 
<p>some html code</p> 
<!-- End bar.html --> 

私がやろうとしてmは何がfoo.htmlという、foo2はにhtmlファイルを分割しています。 htmlとbar.html。 ブロックコメントの数が不明です。ブロックの名前として。 は、これまでのところ私はこのawkのライン

awk '/<!-- Begin (.*?)-->/ {f=$1} f{print > f} /<!-- End \1 -->/{close f; f=""}' index.html 

を持っている。しかし、それは正しく動作しません。

この問題を解決する方法やその他の方法があれば教えてください。

+2

foo2.htmlには何が起こるはずですか?そして、なぜあなたはこれを行うためにawkを使用していますか? –

+0

申し訳ありませんが、foo2.htmlも分割する必要があります。私は実際にawkが仕事をすることができると思った。 –

+0

foo2.htmlを別のfoo2.htmlファイルに分割する必要があるということですか?この詳細を追加するには、質問を更新する必要があります。 –

答えて

1

私は質問ではっきりしていませんが、しかし、具体的なコメントがあれば、正規表現の範囲を与えることができます。 foo2.html部分もfoo.htmlに追加されます。このような何か -

awk ' 
/Begin foo.html/,/End foo.html/{print $0 > "foo.html"} 
/Begin bar.html/,/End bar.html/{print $0 > "bar.html"}' index.html 

テスト:

[jaypal:~/Temp] cat index.html 
<!-- Begin foo.html --> 
<p>some html code</p> 

    <!-- Begin foo2.html --> 
    <p>some html code</p> 
    <!-- End foo2.html --> 

<!-- End foo.html --> 

<!-- Begin bar.html --> 
<p>some html code</p> 
<!-- End bar.html --> 

[jaypal:~/Temp] awk '/Begin foo.html/,/End foo.html/{print $0 > "foo.html"} 
/Begin bar.html/,/End bar.html/{print $0 > "bar.html"}' index.html 

[jaypal:~/Temp] cat foo.html 
<!-- Begin foo.html --> 
<p>some html code</p> 

    <!-- Begin foo2.html --> 
    <p>some html code</p> 
    <!-- End foo2.html --> 

<!-- End foo.html --> 

[jaypal:~/Temp] cat bar.html 
<!-- Begin bar.html --> 
<p>some html code</p> 
<!-- End bar.html --> 
+0

ありがとう、私の場合、私はfoo.htmlかfoo2.htmlを知らないのですが、私は/ <! - Begin(。*?) - >/ –

1
$ cat input.txt 
<!-- Begin foo.html --> 
<p>some html code</p> 

    <!-- Begin foo2.html --> 
    <p>some html code</p> 
    <!-- End foo2.html --> 

<!-- End foo.html --> 

<!-- Begin bar.html --> 
<p>some html code</p> 
<!-- End bar.html --> 

$ awk '/<!-- Begin/{stack[sp++]=$3; print ">>>", $3; next}; /<!-- End/{sp--; print "<<<", $3; next}; {if(sp>0) print > stack[sp-1]}' input.txt 
>>> foo.html 
>>> foo2.html 
<<< foo2.html 
<<< foo.html 
>>> bar.html 
<<< bar.html 

$ for i in {foo,foo2,bar}.html; do echo "=====$i======"; cat $i; done 
=====foo.html====== 
<p>some html code</p> 


=====foo2.html====== 
    <p>some html code</p> 
=====bar.html====== 
<p>some html code</p> 

私はdebug msgを追加しました。 print ">>>", $3を削除した後、コードはかなり短くなります。最後に

$ awk '/<!-- Begin/{stack[sp++]=$3; next}; /<!-- End/{sp--; next}; {if(sp>0) print > stack[sp-1]}' input.txt 
は、あなたが(インデントが正しくない)HTMLを再フォーマットする必要があります!

+0

を使用しています。 OPが望むもの –