Reputation: 31
I have a list of folders in current directory with name "S01.result" up to "S15.result", amongst other stuff. I'm trying to write a script that cd into each folder with name pattern "sXX.result" and do something within each subdirectory.
This is what I'm trying:
ext = ".result"
echo -n "Enter the number of your first subject."
read start
echo -n "Enter the number of your last subject. "
read end
for i in {start..end};
do
if [[i < 10]]; then
name = "s0$i&ext"
echo $name
else
name = "s$i$ext"
echo $name
fi
#src is the path of current directory
if [ -d "$src/$name" ]; then
cd "$src/$name"
#do some other things here
fi
done
Am I concatenating the filename correctly and am I finding the subdirectory correctly? Is there any better way to do it?
Upvotes: 3
Views: 239
Reputation: 3288
You said you need to cd
into each folder that matches the pattern, so we can iterate through all files/folders in current directory for those subdirectories that match the desired pattern.
#!/bin/bash
# Get current working directory
src=$(pwd)
# Pattern match as you described
regex="^s[0-9]{2}\.result$"
# Everything in current directory
for dir in "$src"/*; do
# If this is a directory that matches the pattern, cd to it
# Will early terminate on non-directories
if test -d $dir && [[ $dir =~ $regex ]]; then
cd "$dir"
# Do some other things here
fi
done
Upvotes: 2