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?

1 Answer 1

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).

2
  • 1
    Wat if I do this grep mystring * | sort | uniq ? Doesn't this search in all the current dir files? Commented Feb 15, 2016 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). Commented Feb 15, 2016 at 13:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.