perl one-liner 只保留所需的行 [英] perl one-liner to keep only desired lines
问题描述
我有一个这样的文本文件 (input.txt):
I have a text file (input.txt) like this:
NP_414685.4: 15-26, 131-138, 441-465
NP_418580.2: 493-500
NP_418780.2: 36-48, 44-66
NP_418345.2:
NP_418473.3: 1-19, 567-1093
NP_418398.2:
我想要一个 perl 单行,它只保留文件中:"后跟数字范围的那些行(这意味着,在这里,包含NP_418345.2:"和NP_418398.2:"的行被删除).为此,我尝试过:
I want a perl one-liner that keeps only those lines in file where ":" is followed by number range (that means, here, the lines containing "NP_418345.2:" and "NP_418398.2:" get deleted). For this I have tried:
perl -ni -e "print unless /: \d/" -pi.bak input.txt del input.txt.bak
但它显示的输出与输入文件完全相同.我可以在这里匹配的确切模式是什么?谢谢
But it shows exactly same output as the input file. What will be the exact pattern that I can match here? Thanks
推荐答案
首先,print until
的意思是 print if not
—— 与你想要的相反.
First, print unless
means print if not
-- opposite to what you want.
更重要的是,同时使用 -n
和 -p
是没有意义的,当你执行 -p
覆盖时另一个.当它们都打开输入文件并设置行循环时,-p
还为 每次 迭代打印 $_
.所以有了它,你就重印了每一行.请参阅 perlrun.
More to the point, it doesn't make sense using both -n
and -p
, and when you do -p
overrides the other. While both of them open the input file(s) and set up the loop over lines, -p
also prints $_
for every iteration. So with it you are reprinting every line. See perlrun.
最后,您似乎要删除 .bak
文件...?那就别做了.只使用 -i
Finally, you seem to be deleting the .bak
file ... ? Then don't make it. Use just -i
总和
perl -i -ne 'print if /:\s*\d+\s*-\s*\d+/' input.txt
如果您确实想保留备份文件,请使用 -i.bak
而不是 -i
If you do want to keep the backup file use -i.bak
instead of -i
您可以使用 B::Deparse 查看与带有特定选项的单行代码等效的代码(通过 O 模块)
You can see the code equivalent to a one-liner with particular options with B::Deparse (via O module)
试试:perl -MO=Deparse -ne 1
和 perl -MO=Deparse -pe 1
这篇关于perl one-liner 只保留所需的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!