ShamanWarrior
ShamanWarrior

Reputation: 31

How to grep files that contains ONLY numbers?

Im trying to grep names of txt files containing numbers and numbers only, but I have no idea if grep is even suitable for that job.

if I have files like below...

FILE1: 12324
FILE2: 12345q
FILE3: qqerxv

It should give me only the name of FILE1.

I've tried grep -r -l [a-zA-Z] but that gives me the opposite.

What pattern should I use? What should I do to grep everything but files containing anything but numbers

How do I grep files that contains ONLY numbers?

Upvotes: 3

Views: 10466

Answers (4)

Dasarathan Sampath
Dasarathan Sampath

Reputation: 93

use

grep -x -E "[0-9]+"

-x will force for the entire text -E extended regular expression to use +

Upvotes: 0

Jotne
Jotne

Reputation: 41446

These awk should do:

awk '!/[^0-9]/ {print FILENAME}' FILE*
awk '!/[a-zA-Z]/ {print FILENAME}' FILE*
FILE1

It will print all Filenames from files that do only contain digits

Upvotes: 0

nocut
nocut

Reputation: 28

Please use the regex pattern: \b([0-9])*\b

This should help you to grep the lines that contains the only numbers.

Now to extract the name of the file from the output of above you may cut command, by piping the output of grep? tocut`, i.e.

cat data.txt | grep \b([0-9])*\b | cut -f 1 -d ":"

Here I have assumed you have stored the list of your filenames in the file data.txt.

Options used in grep:

  • \b -- word boundary
  • [0-9] -- match only a digit
  • () -- grouping

Options used in cut:

  • f -- to select the field
  • d -- to specify delimiter

Upvotes: 0

Thomas Q
Thomas Q

Reputation: 890

grep -r -L "[^0-9 ]" .

[^0-9 ] will match anything that doesn't contain digits or spaces (thought that would be fitting or else all files that contain spaces and number would be discarded).

The -L flag is --files-without-match, so this basically gives you files that DO contain digits or spaces.

Inverting the search is way better than searching for files containing [a-zA-Z] because this search would break if any other special characters (_=+&...) are in there.

Btw, the -r flag will search recursively in the current directory. If you want only to search the files in the current directory I suggest removing the -r and substituting the . with an * or just simply substitute it with the name of a single file you want to match.

Upvotes: 4

Related Questions