Perl - 如果文件只有指定的字符,则从命令行检测 [英] Perl - Detect from command line if file has only a specified character
问题描述
使用perl,如果指定的文件只包含指定的字符,例如'0',如何从命令行检测?
我尝试了
^ 0 * $)/ yes /'filename
但它无法检测所有条件,例如多行,非零线。
输入示例 -
只包含零的文件 -
0000000000000000000000000000000000000000000000000000000000
输出 - yes
空文件
pre>
输出 -
no
包含零,但有换行符
000000000000000000
000000000000
输出 -
no
0324234-234-324000324200000
输出 -
no
解决方案
-0777
导致$ /
设置为undef
perl -0777ne'print / ^ 0 + $ / ? yes:no'file
或
$ b bperl -0777nE'say / ^ 0 + $ /? yes:no'file#5.10+
使用
\ z
而不是$
,如果想确保没有尾随换行符。 (文本文件应包含尾随换行符。)This was the original question.
Using perl, how can I detect from the command line if a specified file contains only a specified character(s), like '0' for example?
I tried
perl -ne 'print if s/(^0*$)/yes/' filename
But it cannot detect all conditions, for example multiple lines, non-zero lines.
Sample input -
A file containing only zeros -
0000000000000000000000000000000000000000000000000000000000000
output -
"yes"
Empty file
output -
"no"
File containing zeros but has newline
000000000000000000 000000000000
output -
"no"
File containing mixture
0324234-234-324000324200000
output -
"no"
解决方案
-0777
causes$/
to be set toundef
, causing the whole file to be read when you read a line, soperl -0777ne'print /^0+$/ ? "yes" : "no"' file
or
perl -0777nE'say /^0+$/ ? "yes" : "no"' file # 5.10+
Use
\z
instead of$
if want to make sure there's no trailing newline. (A text file should have a trailing newline.)这篇关于Perl - 如果文件只有指定的字符,则从命令行检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!