Mark
Mark

Reputation: 6464

Match group of files, excluding one specific file, in Bash

I have bunch of files having the following names: text.sh, text, text.1, text.2 etc. How can I refer to all these files, except text.sh, in my bash script? I tried to use text* but it also matches text.sh

Upvotes: 0

Views: 101

Answers (4)

Rogelio Prieto
Rogelio Prieto

Reputation: 359

Try this command, will appear the files that does NOT match with text.sh:

 ls -l !(text.sh) 

This will be your output:

-rw-rw-r-- 1 myuser mygroup 0 sep 13 10:44 text
-rw-rw-r-- 1 myuser mygroup 0 sep 13 10:45 text.1
-rw-rw-r-- 1 myuser mygroup 0 sep 13 10:45 text.2

By the way, another solution, more complex:

  ls -l !(text.sh|!(text?(.)*));

Upvotes: 1

Benjamin W.
Benjamin W.

Reputation: 52102

I'd do it like this:

for file in text*; do
    [[ $file == 'test.sh' ]] && continue
    # Processing
done

This avoids all the edge cases encountered with extended globs. If you want it to be portable to any POSIX shell, you could use [ ] instead:

for file in text*; do
    [ "$file" = 'test.sh' ] && continue
    # Processing
done

Upvotes: 0

Barmar
Barmar

Reputation: 780673

Enable extended globbing and use an exclusion list.

shopt -s extglob
echo text!(.sh)

Upvotes: 3

wcarhart
wcarhart

Reputation: 2773

@Barmar's answer is essentially the same as mine, but it's generally bad practice to iterate over the output of ls in a shell script. There are many different options for iteration, one is a for loop:

shopt -s extglob
for file in text!(.sh) ; do ... ; done

See also: https://unix.stackexchange.com/questions/164025/exclude-one-pattern-from-glob-match

Upvotes: 2

Related Questions