justaguy
justaguy

Reputation: 3022

bash to list files of a certain type but only if condition is met

I am trying to list specific file extension .vcf using bash. The issue I am having is that there might be multiple .vcf in the directory, but the one that is needed only does not have a _ in them rather it is just in the format xxx.vcf (name.vcf). I am not sure how to do this but the below seems close. Thank you :).

Directory files

123.vcf
123_count.txt
123_variant_list.vcf

bash

select file in $(cd /home/file/overall/stats;ls *.{vcf});do break;done
        echo $file

desired output

123.vcf

Upvotes: 1

Views: 73

Answers (3)

Mad Physicist
Mad Physicist

Reputation: 114440

One way would be to use find and a simple regex:

find -regex '[^_]*.vcf'

If you do not want to use a regex, you can follow @123's suggestion and negate part of the match with regular globbing:

find ! -name '*_*' -name '*.vcf'

If you explicitly want to omit subdirectories:

find -maxdepth 1 ...

If the leading ./ that find prepends when you do not explicitly specify a path bothers you, you can use basename to remove it:

basename $(find ...)

If you plan on passing the path to some other program, the leading ./ should not be a problem.

Upvotes: 3

cb0
cb0

Reputation: 8613

You could list all files and the grep those that do not contain a "_".

$ file=$(ls | grep "vcf" | grep -v "_")


$ ls | grep vcf
123.vcf
123_count.txt
123_variant_list.vcf

$ echo $file
123.vcf

Upvotes: 1

fedorqui
fedorqui

Reputation: 290115

Enable extglob and say:

$ echo !(*_*).vcf
123.vcf

That is: match all files not containing any _ and ending with .vcf:

$ ls -1
123_count.txt
123.txt
123_variant_list.vcf
123.vcf
$ shopt -s extglob
$ echo !(*_*).vcf
123.vcf

From Bash Reference Manual → 4.3.2 The Shopt Builtin:

extglob

If set, the extended pattern matching features described above (see Pattern Matching) are enabled.

More info in tzot's answer to How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?:

!(pattern-list) Matches anything except one of the given patterns

Upvotes: 5

Related Questions