Find to delete lines with pattern and even or odd number

In the below directory I am trying to delete all lines with a .bam extention that have the pattern IonCode_ followed by an even number. I am also trying to delete all lines with a .fastq extention that have the pattern IonCode_ followed by an odd number. I was going to use find but can see all lines result with the code as is. Thank you :).

IonCode_0281.bam     --- keep
IonCode_0282.bam     --- delete
IonCode_0281.fastq   --- delete
IonCode_0282.fastq   --- keep
find . -maxdepth 1 -type f -iname "IonCode_[02468]*.bam" #delete    --- remove even
find . -maxdepth 1 -type f -iname "IonCode_[13579]*.fastq" #delete    --- remove odd

desired

IonCode_0281.bam
IonCode_0282.fastq
find . -maxdepth 1 -type f | awk -F'[._]' '($NF=="bam" && !($(NF-1)%2)) || ($NF=="fastq" && $(NF-1)%2) {print "rm " $0}'

When happy with the results, pipe to "sh": ..... | sh

1 Like

Select on the last digit

find . -maxdepth 1 -type f -iname "IonCode_*[02468].bam" -print
find . -maxdepth 1 -type f -iname "IonCode_*[13579].fastq" -print

To really delete, replace -print with -delete.

2 Likes

In case you get charged by the find :

find . -maxdepth 1 -type f \( -iname "IonCode_*[13579].fastq" -o -iname "IonCode_*[02468].bam" \) -delete

or (gnu-ish)

find . -maxdepth 1 -type f -iregex '.*/IonCode_.*\([02468][.]bam\|[13579][.]fastq\)' -delete
1 Like

I made a typo in the filenames, I apologize. The bold section is the even or odd number used. I think the 00-000 is being used and can not seem to have it look before the 00-000 . Thank you :).

IonCode_0281-00-000.bam     --- keep
IonCode_0282-00-000.bam     --- delete
IonCode_0281-00-000.fastq   --- delete
IonCode_0282-00-000.fastq   --- keep
find . -maxdepth 1 -type f -iregex '.*/IonCode_.*\([0-9]+[02468]-[0-9]*-[0-9]*[.]bam\|[0-9]+[13579]-[0-9]*-[0-9]*[.]fastq\)' -delete
1 Like

Thank you all :).