I need to find all the strings which end with '.txt' inside text file. I tried:
grep 'txt$' myFileBut it gives out whole lines, not only the strings which end with '.txt'
11 Answer
If you want to list only the matched "strings," you should use the -o option of grep:
grep -o '\w*\.txt\b' myFileor
grep -Eo '\w+\.txt\b' myFileThe 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 |
|---|---|
\w | any 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) |
\b | match 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.