First off, I apologize if this is a noob question - I am quite new to bash scripting.
I have a directory containing many types of files and folders. I need to perform a set of actions upon all files matching a certain pattern. This is the pattern: prefix_suffix.ext. The _suffix.ext is the exact same for all the target files and only the prefix portion is variable.
Is it possible (and if so, how?) to, within bash, loop over all filenames matching the pattern and have one variable for filename and one for prefix within the loop. I'd like to avoid external tools such as sed.
Any help would be greatly appreciated! Thank you!
for filename in *_suffix.ext; do
prefix="${filename%_suffix.ext}"
#do your thing here
done
This uses the POSIX suffix stripping feature (see man dash and type /suffix<enter> to search for suffix):
${parameter%word} Remove Smallest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the suffix matched by the pattern deleted.
(%% would strip the longest matching suffix, but since we're using a literal suffix here instead of a glob pattern, the two are the same in this case).
Runnable example:
for filename in pre1_suffix.ext pre2_suffix.ext; do
prefix="${filename%_suffix.ext}"
echo "$prefix"
done
will print
pre1
pre2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With