「メモ」カテゴリーアーカイブ

テキストの任意の箇所に文字列挿入

博論に使うテキストデータの下処理の関係で、備忘録。

以下のようなCHAT形式のテキストファイルがあるとする。

@Begin
@Participants:	JAN0180
*JAN0180:	I do not agree with having broad knowledge of many academic subjects .
*JAN0180:	I think it is no use to learn them .
*JAN0180:	Have you ever use many academic subjects to work or live ?
%P
*JAN0180:	We learn something that is useless for us when we are students .
*JAN0180:	In fuct , I did not use knowledge that is history , biology and math to live or develope my ideas .
*JAN0180:	In addition , the thing I learned when I was a high school student is different from the things I am learning now in university .
%P
@End

やりたいことは、@Begin、@Participants、%P、@End以外の改行直後に文字列を挿入したい。例えば、今回の例だと%INSERT:という文字列を挿入したい。
この例だと、「*JAN0180:本文」という文字列の改行直後にそれぞれ%INSERTを挿入していきたい。

@Begin
@Participants:	JAN0180
*JAN0180:	I do not agree with having broad knowledge of many academic subjects .
%INSERT:
*JAN0180:	I think it is no use to learn them .
%INSERT:
*JAN0180:	Have you ever use many academic subjects to work or live ?
%INSERT:
%P
*JAN0180:	We learn something that is useless for us when we are students .
%INSERT:
*JAN0180:	In fuct , I did not use knowledge that is history , biology and math to live or develope my ideas .
%INSERT:
*JAN0180:	In addition , the thing I learned when I was a high school student is different from the things I am learning now in university .
%INSERT:
%P
@End

こんな感じで。

処理したいテキストの本文の前には、「*JAN0180」という形で、アスタリスクがついているので、そこを指定して置換すればうまくいくはず。

置換前:(\*.+\n)
置換後:$1%INSERT:\t\n

単に、アスタリスクを指定して、後方参照するだけでうまく行く。
テストでうまく行ったので、後は対象のディレクトリ内すべてのテキストファイルに対して同じ処理をする。Terminal上でperlの1行スクリプトを書いて置換してやれば一瞬で500ファイルの置換が終わった。

perl -pi -e 's/(\*.+\n)/$1%INSERT:\t\n/g' *.txt

こんな感じで。