This是最初的问题。
使用perl,如何从命令行检测指定的文件是否只包含指定的字符,例如“0”?
我试过
perl -ne 'print if s/(^0*$)/yes/' filename
但它无法检测所有条件,例如多行,非零行。
示例输入 -
仅包含零的文件 -
0000000000000000000000000000000000000000000000000000000000000
输出 - "yes"
Empty file
输出 - "no"
包含零但包含换行符的文件
000000000000000000
000000000000
输出 - "no"
包含混合物的文件
0324234-234-324000324200000
输出 - "no"
答案 0 :(得分:1)
-0777
会导致$/
设置为undef
,导致读取行时读取整个文件,所以
perl -0777ne'print /^0+$/ ? "yes" : "no"' file
或
perl -0777nE'say /^0+$/ ? "yes" : "no"' file # 5.10+
如果要确保没有尾随换行符,请使用\z
代替$
。 (文本文件应该有一个尾随换行符。)
答案 1 :(得分:1)
要打印yes
如果文件包含至少一个 0
字符且没有其他,否则no
,
perl -0777 -ne 'print /\A0+\z/ ? "yes" : "no"' myfile
答案 2 :(得分:0)
我怀疑你想要一个更通用的解决方案,而不仅仅是检测零,但我没有时间为你写明天。无论如何,这是我认为你需要做的事情:
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()逐个字符进行测试。如果你想忽略换行符和回车符,只需使用“tr”在步骤2之前从“s”中删除它们。