1

Assuming I want to write a line which prints out lines which match a specific string without repeating duplicate lines .. I want to search for this string in the files of the current directory:

grep mystring ***What to put here?** | sort | uniq

How can I search in all of the current dir files?

2
find . ! -name . -prune -type f -exec cat {} + |
  grep mystring |
  LC_ALL=C sort -u

Or:

find . ! -name . -prune -type f -exec cat {} + | awk '
  /mystring/ && !seen[$0]++'

With GNU grep:

LC_ALL=C grep -hr --exclude-dir='?*' mystring | LC_ALL=C sort -u

Or with zsh and GNU grep:

grep -h mystring ./*(D.) | LC_ALL=C sort -u

To also search in files in sub-directories, recursively:

find . -type f -exec cat {} + |
  grep mystring |
  LC_ALL=C sort -u

Or:

find . -type f -exec cat {} + | awk '
  /mystring/ && !seen[$0]++'

With GNU grep:

grep -hr mystring | LC_ALL=C sort -u

Note that all those solutions also look inside hidden files (and files inside hidden directories), but not in non-regular files and wouldn't follow symlinks (unless you use some old version of GNU grep with -r).

  • 1
    Wat if I do this grep mystring * | sort | uniq ? Doesn't this search in all the current dir files? – Sijaan Hallak Feb 15 '16 at 13:00
  • 3
    @SijaanHallak, that would also look inside non-regular files, that would not look inside hidden files. That would fail if some file names start with -. That could fail if you have a large number of non-hidden files in the current directory. If there's more than one file, that would include the file names in the output (GNU grep has a -h option to remove them). – Stéphane Chazelas Feb 15 '16 at 13:13

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.