How to find a line that contains numerical values?

i.e. I want to find some line that has some digits in it. I am using Ubuntu 16.04 . Can I do this with the grep command ?


Yes you can!

grep '[0-9]' file

Replace file with the name of your file...

  • 5
    An alternative version using the locale-independent class is grep '[[:digit:]]' file. – Paddy Landau Dec 6 '16 at 9:20

Here are a few choices, all using the following test input file:

bar 12

All of these commands will print any input lines containing at least one number:

$ grep '[0-9]' file
bar 12
$ grep -P '\d' file
bar 12
$ awk '/[0-9]/' file
bar 12
$ sed -n '/[0-9]/p' file
bar 12
$ perl -ne 'print if /\d/' file
bar 12
$ while read line; do [[ $line =~ [0-9] ]] && printf '%s\n' "$line"; done < file
bar 12
$ while read line; do [[ $line = *[0-9]* ]] && printf '%s\n' "$line"; done < file
bar 12

Nobody mentioned python yet, so here it is:

bash-4.3$ cat file
barfoo foo bar
barfoo 123 foobar 321
bash-4.3$ python -c 'import re,sys;matched=[line.strip() for line in sys.stdin if re.findall("[0-9]",line)];print "\n".join(matched)' < file 
barfoo 123 foobar 321

Basic idea how this works is that we give file as stdin input, python code reads all lines in stdin and uses re.findall() function from the regex module to match lines, and finally prints out the list of those lines. A bit lengthy , but works. Some parts can be shortened a lot, say like this:

python -c 'import re,sys;print "\n".join([l.strip() for l in sys.stdin if re.findall("[0-9]",l)])' < file 

On side note, this is python2. Use print function with parentheses to adapt it to python3

  • Python 2 supports print() with parentheses too, just add them and the code will (probably) work on both Py2 and Py3. – gronostaj Dec 3 '16 at 11:12
  • @gronostaj Yep, python 2 does allow print() although the behavior of python 3 is different in a lot of respects.In this case it will work, but there's a lot of other cases where it won't. I'll keep my answer the way it is. People should be aware that python 2 and 3 are somewhat different. – Sergiy Kolodyazhnyy Dec 3 '16 at 18:52
  • My answer was downvoted. Why ? – Sergiy Kolodyazhnyy Dec 8 '16 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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