我有一个文本文件,我想搜索如下标签:
<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>
Run Code Online (Sandbox Code Playgroud)
并生成以下内容并将它们写入新的文本文件。
Type II human complement C2 deficiency
Huntington disease
hereditary breast and ovarian cancer
myopathy
Run Code Online (Sandbox Code Playgroud)
这看起来像一种 XML 或类似的标记语言文件。这样的文件不应该用简单的正则表达式解析,以免被唤醒??????????这????小马?. 您应该使用特定于该标记的解析器和您最喜欢的脚本语言。
这看起来像 OMIM 或 HPO 数据,在这种情况下,您应该能够获得简单的文本文件并简化事情。如果你不能而且真的需要解析这个文件,你可以在 perl 中做到这一点:
perl -lne '/<.*?>([^<>]+)/ && print $1' foo.txt
Run Code Online (Sandbox Code Playgroud)
但是,如果每行有多个标记,或者标记的内容可以跨越多行,或者标记的数据可以包含>
或,则这将中断<
。如果您的所有信息始终介于 之间<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
};
}
Run Code Online (Sandbox Code Playgroud)
将此脚本另存为foo.pl
或其他,使其可执行并在您的文件上运行它:
./foo.pl file.txt
Run Code Online (Sandbox Code Playgroud)
例如:
$ 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
Run Code Online (Sandbox Code Playgroud)
不过,我再次强调,如果(很可能)您的文件比上面的示例更复杂,这将失败,并且需要更复杂的方法。