Grep lines that end with numbers

Viewed 10228

I have a list of lines like:

Spend: 4,100
Spend2: 2,200
Spend3: 300
Spend4: 1,590
Spend5: 

and I'm trying to grep just the lines that end with numbers

I tried

grep "[0-9]+$" filename.txt > filtered.txt
grep "\d$" filename.txt > filtered.txt

but none of these worked

3 Answers

The + operator is not supported by traditional grep, whose regular expression repertoire is very limited.

All you really care about is whether the last character is a digit, so

grep '[0-9]$' filename.txt

should do what you want. Other approaches include

grep -E '[0-9]+$' filename.txt   # use extended regex repertoire
grep '[0-9]\+$' filename.txt    # POSIX BRE extended
grep -P '\d+$' filename.txt    # PCRE extended; not portable

Notice how I use single quotes throughout. Double quotes introduce additional complications especially with backslashes which you probably want to avoid.

On Basic regular expressions mode you should specify the pattern in the following way:

grep '[0-9]\+$' filename.txt > filtered.txt

In basic regular expressions the meta-characters ‘?’, ‘+’, ‘{’, ‘|’, ‘(’, and ‘)’ lose their special meaning; instead use the backslashed versions ‘\?’, ‘\+’, ‘\{’, ‘\|’, ‘\(’, and ‘\)’.

For extended regular expressions you should use egrep or grep -E.

Related