I Am trying to exclude directories from grep matches, i have tried with --exclude-dir=PATTERN method. But its not working.
ls | grep -E "^Acct" --exclude-dir=Acct
File Structure
Acct/ ---> directory needs to be excluded from grep
AcctReq/ ---> directory needs to be excluded from grep
AcctAdd.txt
AcctInq.txt
AcctMod.txt
AcctTrnInq.txt
CardInq.txt
CardHold.txt
Cardacq.txt
In Above files I am using ls | grep -E "^Acct" command to get only the files starting with Acct, But it is considering the directories as well.
Output:
Acct/
AcctReq/
AcctAdd.txt
AcctInq.txt
AcctMod.txt
AcctTrnInq.txt
Expected Output:
AcctAdd.txt
AcctInq.txt
AcctMod.txt
AcctTrnInq.txt
CodePudding user response:
--exclude-dir is used to skip directories when running a recursive grep. It's meaningless when you're piping input to grep, since there are no directories or filenames to skip.
If you want to exclude matches from the data being piped to grep use -v.
ls | grep -v 'Acct.*/'
CodePudding user response:
Your pattern is simple enough for a standard glob, so why not doing it with find?
- GNU
find . -maxdepth 1 -type f -name 'Acct*' -printf '%f\n'
AcctAdd.txt
AcctInq.txt
AcctMod.txt
AcctTrnInq.txt
- POSIX
find . ! -name . -prune -type f -name 'Acct*' -exec sh -c 'printf %s\\n "${@#./}"' _ {}
