Search code examples
bashshellgrepfind

to Avoid catching similar folder names


I'm doing a bash script and it needs to be generated first a text file with the paths that it will run the script. However, there are some paths that are similar in name and the grep command does not work properly to me.

The command used is:

find /base/path/ -type d | grep -i "$1" | grep -i ".root" | grep  -i "Inv" | grep -v "deleted" 

This is my current ouput:

/base/path/lbasaur/Inv/DATA18/WenuL/group.phys-hdbs.mc16_13TeV.root
/base/path/lbasaur/Inv/DATA18/WenuL/group.phys-hdbs.mc16_13TeV_1.root
/base/path/lbasaur/InvCR/DATA16/Wenu/group.phys-hdbs.mc16_13TeV.root
/base/path/lbasaur/InvCR/DATA16/Wenu/group.phys-hdbs.mc16_13TeV_1.root
/base/path/lbasaur/InvCR/DATA16/WenuB/group.phys-hdbs.mc16_13TeV_2.root
/base/path/lbasaur/InvCR/DATA16/WenuB/group.phys-hdbs.mc16_13TeV_3.root
/base/path/lbasaur/InvCR/DATA16/WenuB/group.phys-hdbs.mc16_13TeV_4.root


but i only want the paths with 'Inv', not 'InvCR'. So, the names Inv and InvCR are pick up when i use this large command. How can i fix it?


Solution

  • I can see what you are getting at. There is a couple ways to exclude some name from a search you are using one already grep -v "deleted"

    Using this same format we can exclude InvCR:

    find /base/path/ -type d | grep -v 'InvCR'
    

    You can use -prune as well:

    find /base/path/ -path '*InvCR*' -prune -o -type d -print
    

    Realistically you only need to use one find and a grep to accomplish what you want:

    find /base/path/ -path '*deleted*' -prune -o -path '*InvCR*' -prune -o -type d -wholename '*Inv*' -print | grep -P '.*'"$1"'.*[.]root'
    

    Note this is case sensitive to conform with your original code.