This是最初的问题。
使用perl,如果指定的文件仅包含指定的字符(例如'0‘),那么如何从命令行检测?
我试过了
perl -ne 'print if s/(^0*$)/yes/' filename但是它不能检测所有的情况,例如多行,非零行.
样本输入-
只包含零的文件-
0000000000000000000000000000000000000000000000000000000000000输出- "yes"
Empty file输出- "no"
包含零但有换行符的文件。
000000000000000000
000000000000输出- "no"
含有混合物的文件
0324234-234-324000324200000输出- "no"
发布于 2013-11-26 19:42:32
-0777导致将$/设置为undef,导致在读取一行时读取整个文件,因此
perl -0777ne'print /^0+$/ ? "yes" : "no"' file或
perl -0777nE'say /^0+$/ ? "yes" : "no"' file # 5.10+如果希望确保没有尾随换行符,请使用\z而不是$。(文本文件应该有一个尾随的换行符。)
发布于 2013-11-26 19:51:42
若要打印yes (如果文件至少包含一个0字符而不包含任何其他字符),否则要打印no,请编写
perl -0777 -ne 'print /\A0+\z/ ? "yes" : "no"' myfile发布于 2013-11-26 21:08:10
我怀疑你想要一个比探测零更通用的解决方案,但我没有时间为你写到明天。总之,我认为你需要做的是:
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”中删除。
https://stackoverflow.com/questions/20226279
复制相似问题