次のタグを検索したいテキストファイルがあります。
<category="SpecificDisease">Type II human complement C2 deficiency</category>
<category="Modifier">Huntington disease</category>
<category="CompositeMention">hereditary breast and ovarian cancer</category>
<category="DiseaseClass">myopathy</category>
次の内容を作成して新しいテキストファイルに書き込みます。
Type II human complement C2 deficiency
Huntington disease
hereditary breast and ovarian cancer
myopathy
ベストアンサー1
これはXMLや類似のマークアップ言語ファイルのように見えます。これらのファイルは目覚めないように単純な正規表現で解析しないでください。TO ͇̹̺ͅ松̴ş̳ TH̘Ë͖́̉ ΠP̯͍̭O̚N̐Y̡。そのタグと好むスクリプト言語に固有のパーサーを使用する必要があります。
これはOMIMまたはHPOデータのように見えます。この場合は、単純なテキストファイルを取得して操作を簡素化できるはずです。このファイルを解析できず、実際に必要な場合はPerlで実行できます。
perl -lne '/<.*?>([^<>]+)/ && print $1' foo.txt
ただし、1行に複数のラベルがある場合、またはラベルの内容が複数行にまたがる可能性がある場合、またはラベルのデータにまたはが含まれている場合、>
これは中止されます<
。あなたのすべての情報いつも間で<category="whatever">blah blah</category>
すべてをより強力に得ることができます(複数行のマークアップコンテンツと埋め込みまたは<
埋め込み>
)。
#!/usr/bin/env perl
## Set the start and end tags
$end="</category>";
$start="<category=.*?>";
## Read through the file line by line
while(<>){
## set $a to one if the current line matches $start
$a=1 if /$start/;
## If the current line matches $start, capture any relevant content.
## I am also removing any $start or $end tags if present.
if(s/($start)*(.+)($end)*/$2/){
push @lines,$2 if $a==1;
}
## If the current line matches $end, capture any relevant content,
## print what we have saved so far, set $a back to 0 and empty the
## @lines array
if(/$end/){
map{s/$end//;}@lines;
print "@lines\n";
@lines=();
$a=0
};
}
このスクリプトをfoo.pl
実行可能にしてファイルから実行するには、別の名前で保存します。
./foo.pl file.txt
たとえば、
$ cat file.txt
<category="SpecificDisease">Type II
human complement C2 deficiency</category>
<category="Modifier">Huntington disease</category>
<category="CompositeMention">hereditary breast < and ovarian cancer</category>
<category="DiseaseClass">myopathy > cardiopathy</category>
$ ./foo.pl file.txt
Type II human complement C2 deficiency
Huntington disease
hereditary breast < and ovarian cancer
myopathy > cardiopathy
しかし、繰り返しますが、ファイルが上記の例よりも複雑な場合は、これは失敗するでしょう。そしてより洗練された方法が必要です。