andrikoulas
andrikoulas

Reputation: 87

Take only the lines with numbers with egrep

i have a file where lines have numbers with characters,only characters and only numbers. I would like to choose the lines with only numbers. I tried egrep '[^[:alpha:]]' filename but i take also lines with chars. Any idea?

AQ
Feb 9, 1999
11:45
45

And i want only

45

Upvotes: 1

Views: 612

Answers (4)

Tom Fenech
Tom Fenech

Reputation: 74596

To match lines containing only numbers, use either "whole line mode" with -x:

grep -xE '[[:digit:]]+' file

or add the line start/end anchors to the regular expression:

grep -E '^[[:digit:]]+$' file

Note that you can replace the character class [:digit:] with the range 0-9 if you are only concerned with matching the ASCII characters from 0 to 9:

grep -xE '[0-9]+' file

Upvotes: 0

karakfa
karakfa

Reputation: 67467

with awk

only lines with digits and nothing else

$ awk '/^[0-9]+$/' file
45

or, exclude any line which has a not digit char

$ awk '!/[^0-9]/' file
45

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246744

I would exclude any line that contains any non-digit character:

grep -v '[^[:digit:]]' file
# ........| negates the character class

Upvotes: 1

df778899
df778899

Reputation: 10931

The regex needs to check that everything on the line is numeric. So a ^ and $ around the expression is needed to match from the start to the end of each line. Also the match will need to be explicitly for digits, rather than non-alpha.

E.g.

 egrep '^[[:digit:]]+$' filename

This worked well against the example in the question.

Upvotes: 1

Related Questions