3

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?

Inian
  • 80,270
  • 14
  • 142
  • 161
ShamanWarrior
  • 31
  • 1
  • 4

3 Answers3

4

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.

Thomas Q
  • 850
  • 4
  • 10
  • 2
    The `[:digit:]` character class is probably safer than 0-9. Then you may consider dealing with `read -r decimal_point thousands_sep < <(locale LC_NUMERIC)` to include these in your pattern. – Léa Gris Aug 28 '19 at 23:36
  • Thank you, thats what i Needed. Im grateful ! – ShamanWarrior Aug 28 '19 at 23:37
0

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
tripleee
  • 175,061
  • 34
  • 275
  • 318
nocut
  • 28
  • 5
0

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

Jotne
  • 40,548
  • 12
  • 51
  • 55