1

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"

Community
  • 1
  • 1
CodeBlue
  • 14,631
  • 33
  • 94
  • 132
  • Are you asking if the file contains one single character? It either contains "0", and that's true, and if there's anything else besides 0, then it's false? – Andy Lester Nov 26 '13 at 19:34
  • Andy, it can contain any number of zeros, but it should have at least one zero. – CodeBlue Nov 26 '13 at 19:36

3 Answers3

1

-0777 causes $/ to be set to undef, causing the whole file to be read when you read a line, so

perl -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.)

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 1
    That will print the whole file if it contains exactly `"0"` or `"0\n"`. I don't think that's what is wanted at all. – Borodin Nov 26 '13 at 19:57
  • @Boridin, Fixed the output. And fixed to matched his updated specs. – ikegami Nov 26 '13 at 20:02
  • It's *"Borodin"*. And the specification hasn't changed. Your response didn't solve any reasonable interpretation of *"if a specified file contains only a specified character(s), like '0' for example"*. Even now you insist on using a dollar anchor when the question says *"File containing zeros but has newline ... output - 'no'"* – Borodin Nov 26 '13 at 21:25
1

To print yes if a file contains at least one 0 character and nothing else, and otherwise no, write

perl -0777 -ne 'print /\A0+\z/ ? "yes" : "no"' myfile
Borodin
  • 126,100
  • 9
  • 70
  • 144
0

I suspect you want a more generic solution than just detecting zeroes, but I haven't got time to write it for you till tomorrow. Anyway, here is what I think you need to do:

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"

If your file is big and you don't want to hold two copies in memory, just test character by character using substr(). If you want to ignore newlines and carriage returns, just use "tr" to delete them from "s" before step 2.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432