Perl-从命令行检测文件是否只有指定字符

Perl-从命令行检测文件是否只有指定字符,perl,command-line,Perl,Command Line,这是最初的问题 使用perl,如何从命令行检测指定文件是否只包含指定字符,例如“0” 我试过了 perl -ne 'print if s/(^0*$)/yes/' filename 但它不能检测所有条件,例如多行、非零行 样本输入- 仅包含零的文件- 0000000000000000000000000000000000000000000000000000000000000 输出-“是” 输出-“否” 包含零但有换行符的文件 000000000000000000 000000000000 输

这是最初的问题

使用perl,如何从命令行检测指定文件是否只包含指定字符,例如“0”

我试过了

perl -ne 'print if s/(^0*$)/yes/' filename
但它不能检测所有条件,例如多行、非零行

样本输入-

仅包含零的文件-

0000000000000000000000000000000000000000000000000000000000000
输出-
“是”

输出-
“否”

包含零但有换行符的文件

000000000000000000
000000000000
输出-
“否”

包含混合物的文件

0324234-234-324000324200000

输出-
“no”

-0777
导致将
$/
设置为
未定义
,导致在读取行时读取整个文件,因此

perl -0777ne'print /^0+$/ ? "yes" : "no"' file


如果要确保没有尾随换行符,请使用
\z
而不是
$
。(文本文件应该有一个尾随的换行符。)

要打印
yes
,如果文件至少包含一个
0
字符而没有其他字符,否则
no
,请写入

perl -0777 -ne 'print /\A0+\z/ ? "yes" : "no"' myfile

我想你想要一个比检测零更通用的解决方案,但我明天才有时间给你写。无论如何,我认为你需要做的是:

1. Slurp your entire file into a single string "s" and get its length (call it "L")
2. Get the first character of the string, using substr(s,0,1)
3. Create a second string that repeats the first character "L" times, using firstchar x L
4. Check the second string is equal to the slurped file
5. Print "No" if not equal else print "Yes"

如果文件很大,并且不想在内存中保存两个副本,只需使用substr()逐个字符进行测试。如果要忽略换行符和回车符,只需在步骤2之前使用“tr”将其从“s”中删除。

是否询问文件是否包含一个字符?它或者包含“0”,这是真的,如果除0之外还有其他内容,那么它是假的?Andy,它可以包含任意数量的零,但至少应该有一个零。如果它正好包含
“0”
“0\n”
,则将打印整个文件。“我认为这根本不是我们想要的。”鲍里丁,修正了输出。修正了他最新的规格,是“Borodin”。而且规格没有改变。您的回答没有解决“如果指定的文件只包含指定的字符(例如“0”)的任何合理解释。即使现在,当问题是“包含零但有换行符的文件…输出-‘否’”时,您仍然坚持使用美元锚定,而不适用于包含单个0或多个0的文件。
perl -0777 -ne 'print /\A0+\z/ ? "yes" : "no"' myfile
1. Slurp your entire file into a single string "s" and get its length (call it "L")
2. Get the first character of the string, using substr(s,0,1)
3. Create a second string that repeats the first character "L" times, using firstchar x L
4. Check the second string is equal to the slurped file
5. Print "No" if not equal else print "Yes"