0

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?

closed as unclear what you're asking by G-Man, Archemar, garethTheRed, taliezin, don_crissti Oct 28 '15 at 8:14

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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 – Arthur2e5 Oct 28 '15 at 4:20
7

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
  • 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 :) – Jonah 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.