What is the best way to test if the complete contents of a file matches a regex, such as
^[0-9]{9}$
i.e., just 9 numbers and nothing else, no line breaks, and not multiple sets of numbers.
Here is one variant I have that I do not really like:
cat -vt curloutput.txt | tr "\n" " " | egrep "^[0-9]{9}$"
Edit
I use the accepted solution like this:
grep --perl-regex "(?m)(?<!.)^\d{9}$(?!.)"
using GNU grep.
This regex matches "comprised of 9 digits" and the (?m)
makes caret and dollar match after/before newlines so it works to prevent multiple lines:
(?m)(?<!.)^\d{9}$(?!.)
The look arounds wrapping the main match ensure the line matched is the only line in the file - ie that there's exactly one line in the file.
See this demonstrated on rubular, see how adding any other characters to the 9-digit input text, even a single newline, will result in a non match
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With