Find line with digits

9,583

Solution 1

Yes you can!

grep '[0-9]' file

Replace file with the name of your file...

Solution 2

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

foo
bar 12
baz

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

Solution 3

Nobody mentioned python yet, so here it is:

bash-4.3$ cat file
foo
foo1bar
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 
foo1bar
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

Share:
9,583

Related videos on Youtube

Avani badheka
Author by

Avani badheka

Updated on September 18, 2022

Comments

  • Avani badheka
    Avani badheka over 1 year

    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 ?

  • gronostaj
    gronostaj over 7 years
    Python 2 supports print() with parentheses too, just add them and the code will (probably) work on both Py2 and Py3.
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy over 7 years
    @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.
  • Paddy Landau
    Paddy Landau over 7 years
    An alternative version using the locale-independent class is grep '[[:digit:]]' file.
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy over 7 years
    My answer was downvoted. Why ?