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 ?
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
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