I want to rename a bunch of files using bash, transforming this file pattern:
prefix - name - suffix.txt
Into this one:
name.txt
For that I wrote the following script:
find . -name "*.txt" | while read f
do
mv "${f}" "${f/prefix - /}"
done
find . -name "*.txt" | while read f
do
mv "${f}" "${f/ - suffix/}"
done
It works, but I'd like to perform the renaming using a single loop. Is it possible?
Another approach, for fun, using regular expressions:
regex='prefix - (.*) - suffix.txt'
for f in *.txt; do
[[ $f =~ $regex ]] && mv "$f" "${BASH_REMATCH[1]}.txt"
done
Actually, using the simple pattern '*.txt' here has two problems:
Using find
complicates the procedure, but is more correct:
find . -maxdepth 1 -regex 'prefix - .* - suffix.txt' -print0 | \
while read -d '' -r; do
[[ $REPLY =~ $regex ]] && mv "$REPLY" "${BASH_REMATCH[1]}.txt"
done
If you have access to GNU sed
, you could use some regex to perform something like:
for i in *.txt; do mv "$i" "$(echo $i | sed -r 's/([^-]*)\s-\s(.*)\s-\s([^-]*)\.txt/\2.txt/')"; done
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