Unix syntax for the grep command for only an ending character

unix

Solution

To find lines that end with a `.` character:

grep '\.$' james

Your `cat` command is unnecessary; `grep` is able to read the file itself, and doesn't need `cat` to do that job for it.

A `.` character by itself is special in regular expressions, matching any one character; you need to escape it with a `\` to match a literal `.` character.

And you need to enclose the whole regular expression in single quotes because the `\` and `$` characters are special to the shell. In a regular expression, `$` matches the end of a line. (You're dealing with some characters that are treated specially by the shell, and others that are treated specially by `grep`; the single quotes get the shell out of the way so you can control what `grep` sees.)

As for the square brackets you used in your question, that's another way to escape the `.`, but it's unusual. In a regular expression, `[abc]` matches a single character that's any of `a`, `b`, or `c`. `[.]` matches a single literal `.` character, since `.` loses its special meaning inside square brackets. The double quotes you used: `["."]` are unnecessary, since `.` isn't a shell metacharacter -- but square brackets are special to the shell, with a similar meaning to their meaning in a regular expression. So your

grep ["."]

is equivalent to

grep [.]

The shell would normally expand `[.]` to a list of every visible file name that contains the single character `.`. There's always such a file, namely the current directory `.` -- but the shell's `[]` expansion ignores files whose names start with `.`. So since there's nothing to expand `[.]` to, it's left alone, and `grep` sees `[.]` as an argument, which just happens to work, matching lines that contain a literal `.` character. (Using a different shell, or the same shell with different settings, could mess that up.)

Note that the shell doesn't (except in some limited contexts) deal with regular expressions; rather it uses file matching patterns, which are less powerful.

Problem

For the file `james`, when I run this command: ``` cat james | grep ["."] ``` I get only the lines that contain a dot. How do I get only the lines that end with a dot?

Original source