0

I have a current script to get all .jpg and .jpeg files in a folder, my bash script is as follows

shopt -s nullglob
CURRENT_IMAGE_FILES=($DIR/*.jpg $DIR/*.jpeg)
echo ${#CURRENT_IMAGE_FILES[@]}
shopt -u extglob

The results being output are as follows (1.jpg , 3.jpg , 5.jpg , 2.jpeg ,4.jpeg). Being that the serach follows all .jpg first then the rest of the .jpeg being found.

The issue with this code is that it get's all jpg files first then gets all jpeg files. I however want to get all jpg and jpeg files in increment as follows (1.jpg, 2.jpeg, 3.jpg, 4.jpeg, 5.jpg)

codeforester
  • 39,467
  • 16
  • 112
  • 140
Jeremiah Lim
  • 179
  • 3
  • 17
  • See [how to sort an array in bash](http://stackoverflow.com/q/7442417/3076724). Note you need numeric sort (`sort -n`). – Reinstate Monica Please Sep 18 '14 at 03:24
  • Or, seeing as you enable extended globbing afterwards anyway, you could use an extended glob pattern to get all the files in one go. You can have `extglob` and `nullglob` at the same time, I believe (your example reads as if you think enabling extglob will turn offf nullglob?) – tripleee Sep 18 '14 at 03:29

1 Answers1

0

Once extglob is set, it's as simple as

shopt -s nullglob extglob
CURRENT_IMAGE_FILES=("$DIR"/*.@(jpg|jpeg))

Since a single pattern will match all the target files, they will be sorted together, as opposed to sorting the files that match just *.jpg, then sorting the files that match *.jpeg. Of course, sorting will only work if the file names are in the right format. 10.jpg would still come before 1.jpg, but there isn't much you can do about that using only globs.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I am getting /var/bash/video.sh: line 37: syntax error near unexpected token `(' /var/bash/video.sh: line 37: ` CURRENT_IMAGE_FILES=("$DIR"/*.@(jpg|jpeg))' 0 – Jeremiah Lim Sep 18 '14 at 04:17
  • How are you running the script? It looks like you are running in POSIX compatibility mode, either by starting the script as `sh /var/bash/video.sh` instead of `bash /var/bash/video.sh`, or by using `#!/bin/sh` instead of `#!/bin/bash` as the shebang. (As an aside, if you are using `bash`-specific features such as arrays, don't use `.sh` as the extension. In fact, you don't need any extension, but `.bash` is better than `.sh`.) – chepner Sep 18 '14 at 11:55