1

I have a text file and I want so scan this text file for a specific number. Lets say the text file is:

asdg32dasdgdsa
dsagdssa11
adad 12345
dsaga

Now I want to search for a number with the length of 5 and print it out (12345).

How can I do this in Linux?

2
  • 3
    Please edit your question and clarify. Do you want a specific number or all numbers with 5 digits? Also, how do you want to deal with decimals? Does 1.2345 have a length of 5 or 6?
    – terdon
    Oct 27 '15 at 16:05
  • Possible duplicate of Grepping number in a file Oct 28 '15 at 4:20
8

You are looking for the grep command:

DESCRIPTION
   grep searches the named input FILEs for lines containing a match to the
   given PATTERN.  If no files are specified, or if the file “-” is given,
   grep  searches  standard  input.   By default, grep prints the matching
   lines.

So, to find the number 12345, run:

$ grep 12345 file
adad 12345

That will print all lines matching 12345. To print only the matched portion of the line, use the -o flag:

$ grep -o 12345 file
12345

To find any stretch of consecutive digits of length 5, you can use one of:

$ grep -o '[0-9][0-9][0-9][0-9][0-9]' file
12345
$ grep -o '[0-9]\{5\}' file
12345
$ grep -Eo '[0-9]{5}' file 
12345
$ grep -Po '\d{5}' file 
12345

To do the same thing but ignore any numbers longer than 5 digits, use:

$ grep -Po '[^\d]\K[0-9]{5}[^\d]*' file
12345
2
grep -o '[0-9][0-9][0-9][0-9][0-9]' file
2
  • This will also list any number with length greater than or equal 5
    – cuonglm
    Oct 27 '15 at 16:09
  • that's right ! but i answered according to the question form , however exist other good answers :)
    – Yunus
    Oct 27 '15 at 16:17
1

POSIXly:

tr -cs '[:digit:]' '[\n*]' <file | grep '^.\{5\}$'

Not the answer you're looking for? Browse other questions tagged or ask your own question.