Detecting pattern at the end of a line with grep

The $ anchor matches the end of a line.

ls -R | grep '\.rar$'

You can also use find for this:

find . -name '*.rar'

In addition to your question please note that .rar does not only match ".rar" but matches every single character (including .) before the rar. In this case probably not a problem but . must be escaped in regexes.

ls -R | grep "\.rar$"

You can also instruct grep to look for your string starting at a word boundary. There is such a boundary between . (a non-word character) and r (a word character). Depending on your grep implementation, the word boundary operator can be \b or possibly \< or [[:<:]] (boundary left of a word only), \> or [[:>:]] (right).

$ ls -R | grep '\brar$'

Example

Say I have this sample data.

$ ls -1
afile.rar
xrar
UFAIZLV2R7.part1.rar.part
UFAIZLV2R7.part2.rar.part

This command would find only the file with the .rar extension.

$ ls -R | grep '\brar$'
afile.rar

How this works?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

Situations where this won't work

If you have files that are named blah-rar these will get detected as well.

$ ls -R | grep '\brar$'
afile-rar
afile.rar

That's because characters other than a alphanumerics are typically considered boundary characters, and so would slip past this approach.

Tags:

Grep