Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match entire contents of file in bash

Tags:

regex

bash

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.

like image 633
tomsv Avatar asked Jun 05 '13 09:06

tomsv


1 Answers

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

like image 181
Bohemian Avatar answered Sep 20 '22 03:09

Bohemian