繁体   English   中英

使用perl从文本文件打印特定行

[英]print specific lines from text file using perl

我正在尝试从文件中的几行分开的行中打印几行。 我认为下面的perl并不是最好的方法,但希望这是一个开始

perl -ne 'if ($. == 5) ($. == 6) ($. == 7) ($. == 10) {print;exit}' file.txt

文件

#Sample = xxxxx
#Sample Type = xxxxxx
#Build = xxxxxxx
#Platform = xxxxxxx
#Display Name= XXXXX  (keep this field without the #)
#identifier = xxxxxx  (keep this field without the #)
#Gender = xxxxx       (keep this field without the #)
#Control Gender = xxxxx
#Control Sample = xxxxx
#Quality = X.XXXXXX   (keep this field without the # and X.XXX)

期望的输出

Display Name= XXXXX  (keep this field without the #)
identifier = xxxxxx  (keep this field without the #)
Gender = xxxxx       (keep this field without the #)
Quality = X.XXXXXX   (keep this field without the # and X.XXX)

您可以使用“ smartmatch”运算符执行以下任务:

perl -ne 's/^#//; @n = (5, 6, 7, 10); print if $. ~~ @n'  file.txt

与其指定要保留的行号,不如通过包含的文本来标识它们要清晰得多

像这样

perl -ne 'print $1 if /^#((Display Name|identifier|Gender|Quality).*)/is' myfile

产量

Display Name= XXXXX
identifier = xxxxxx
Gender = xxxxx
Quality = X.XXXXXX

我不明白您对数据最后一行的评论是什么意思, “保留此字段,不包含#和X.XXX” 您是说“没有# X.XXX”吗? 如果您只想要Quality = here,这很奇怪

perl -ne 'print if $.==5 || $.==6 || $.==7 || $.==10' file.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM