How to grep all the strings which end with '.txt'

I need to find all the strings which end with '.txt' inside text file. I tried:

grep 'txt$' myFile

But it gives out whole lines, not only the strings which end with '.txt'

1

1 Answer

If you want to list only the matched "strings," you should use the -o option of grep:

grep -o '\w*\.txt\b' myFile

or

grep -Eo '\w+\.txt\b' myFile

The man page explains this option like this:

-o, --only-matching

Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

However, you need to define your understanding of "strings." I assume a "string" is something like a "word" described in the man page:

The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]].

In the above example, the two-letter sequences mean this:

Seq.Explanation
\wany alphanumeric character
\w*any number (0 or more) of alphanumeric characters
\w+any number (1 or more) of alphanumeric characters (extended regular expression)
\.the period (.) character itself (. has special meaning and it should be escaped)
\bmatch end of the word (no more alphanumeric characters after the string txt)

Note: The $ character you used in your question means "end-of-line" and it will cause to match strings txt than happen to appear only at end of lines.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like