Search code examples
linuxbashmacosgrepgnu

How to correctly exclude hidden files and directories in linux `grep` result?


I'm trying to exclude hidden files and directories in grep command.

I found some answers here but they're not working:

grep -r --color=always -n -H --exclude-dir='.*' -- 'something'

The reason is that grep will output things like:

./README.md:178:Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
./README.md:179:Plug 'linrongbin16/fzfx.nvim'
./README.md:183:lua require('fzfx').setup()
./README.md:194:    use { "junegunn/fzf", run = ":call fzf#install()" }

They all start with ./, so if simply set --exclude-dir='.*', that will exclude all outputs.

Would you please help me with correct grep command?


Solution

  • For me, the command you wrote doesn't start every filename with a ./. If you add a dot in the end, i.e. -- 'something' ., then it does. Anyway, you can either do:

    grep -r --color=always -n -H --exclude-dir='.*' -- 'something' "$PWD"
    

    Or:

    grep -r --color=always -n -H --exclude-dir='.?*' -- 'something'
    

    Side note, are you sure you want --exclude-dir and not --exclude?