How can I iterate over the contents of a directory on unix without using a wildcard?
I totally understand what the problem is.
I have a bunch of files added as "cat.jpg" and "dog.jpg". I just want to move the "cat.jpg" files to a directory called "cat". It's the same with the 'dog.jpg' files.
for f in *.jpg; do
name=`echo "$f"|sed 's/ -.*//'`
firstThreeLetters=`echo "$name"|cut -c 1-3`
dir="path/$firstThreeLetters"
mv "$f" "$dir"
done
I am getting this message:
mv: cannot stat '*.jpg': No such file or directory
It's good. But I can't find a way to iterate over these images without using this pattern.
I don't want to use a wildcard. The only files are added to "dog" or "cat". I don't need to match. All .jpg files.
Can't I just loop over the contents of a directory without using a wildcard? I know this is a bit of an XY problem, but still I would like to know about it.
source to share
*.jpg
will result in a literal *.jpg
when there are no matching files. Sounds like you need nullglob
. With Bash, you can do this:
#!/bin/bash
shopt -s nullglob # makes glob expand to nothing in case there are no matching files
for f in cat*.jpg dog*.jpg; do # pick only cat & dog files
first3=${f:0:3} # grab first 3 characters of filename
[[ -d "$first3" ]] || continue # skip if there is no such dir
mv "$f" "$first3/$f" # move
done
source to share