5

How do I list all .txt files with their full path that have a word 'Ubuntu' in them. Ignore non-text files. When comparing values you should ignore the case i.e. UBUNTU or ubuNtu or UbUnTu are treated as equal to the search phrase given.

8

GNU grep supports recursive searching based on a glob-pattern, e.g.:

grep --include='*.txt' -ril ubuntu /path/to/dir

If you are not searching for a regular expression, this process will be much faster if you include fixed-string matching (-F). Another optimization is to remove ignore-case (-i) if you know it is not needed.

3

Simple find + grep solution:

find . -type f -name "*.txt" -exec grep -li --binary-files=without-match 'ubuntu' {} \;

grep details:

  • l - suppress normal output; instead print the name of each input file from which output would normally have been printed
  • i - ignore case distinctions, so that characters that differ only in case match each other
  • as OP stated, it should return full path, so you need to have /path/to as path to search or $PWD from current directory instead – αғsнιη Feb 20 '18 at 10:08
  • If I want to search for all text files(.log etc) and not necessarily only .txt files, what should be the command – Sampad Mund Feb 27 '18 at 6:34
  • @SampadMund, just remove -name "*.txt" from the command – RomanPerekhrest Feb 27 '18 at 8:30
3

Some implementation of the grep utility has an -I flag that makes grep ignore binary files. You may also use -i to do a case-insensitive match and -F to match with a fixed string (rather than with a regular expression). If you are looking for separate words you will want to use -w that some grep implementations has. Then, to recurse into subdirectories, you may want to use -R to recursively search files and -l to get the names of the files that contains matches of the pattern. Then we'd like to use --include if we have GNU grep to only look at files with a certain extension.

grep -Fil -IRw --include='*.txt' 'ubuntu' /path/to/top/dir

Standard options used: -F, -i, -l.

Non-standard options used (supported by some grep implementations): -w, -I, -R, --include.


Using find and OpenBSD grep which does not have --include and which uses --binary-files instead of -I (GNU grep also has this flag):

find /path/to/top/dir -type f -name '*.txt' \
    -exec grep -Fil -w --binary-files=without-match 'ubuntu' {} +
1

This is what I typically use:

find /path/to/top/dir -type f -name '*.txt' -exec grep -iHI ubuntu {} \;
  • If I want to search for all text files(.log etc) and not necessarily only .txt files, what should be the command? – Sampad Mund Feb 27 '18 at 6:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.