Quote:
Originally Posted by Reda01
How can I rename files from "a.b.c.d.iso" to "a b c d.iso"
|
I recommend either using the shell argument array, or using
find to list the file names one per line, so you can safely work with file names containing any characters.
Using shell argument array:
Code:
#!/bin/bash
if [ $# -lt 1 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
echo "" >&2
echo "Usage: $0 [ -h | --help ]" >&2
echo " $0 file .." >&2
echo "" >&2
echo "This will transform the name of the specified file(s)." >&2
echo "" >&2
exit 0
fi
for path in "$@" ; do
dir="`dirname "$path"`"
file="`basename "$path"`"
# Split file name and extension
ext=".${file##*.}"
old="${file%.*}"
[ "$old" == "$file" ] && ext=""
new="$old"
# Modify "$new" to suit your needs. Dots to spaces:
new="${new//./ }"
if [ "$new" != "$old" ]; then
mv -vi "$dir/$old$ext" "$dir/$new$ext" || exit $?
fi
done
If you save the above as
fix-file-name, you can then run e.g.
Code:
./fix-file-name *.iso
Check the
shell parameter expansion in the Bash Reference Manual for further tricks you can do to the file names with the above.
If you wish to operate on all files in a directory tree, it's easier to use
find. The following script takes at least one parameter; see
man find for details:
Code:
#!/bin/bash
if [ $# -lt 1 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
echo "" >&2
echo "Usage: $0 [ -h | --help ]" >&2
echo " $0 find-parameters ..." >&2
echo "" >&2
echo "This will transform all file and directory names matching the find-parameters." >&2
echo "See 'man find' for details and explanations." >&2
echo "" >&2
echo "Example:" >&2
echo " $0 . -name '*.iso'" >&2
echo "" >&2
exit 0
fi
EOS="`echo -en '\0'`"
find "$@" -depth -printf '%p\0' | while read -d "$EOS" path ; do
dir="`dirname "$path"`"
file="`basename "$path"`"
ext=".${file##*.}"
old="${file%.*}"
[ "$old" == "$file" ] && suffix=""
new="$old"
# Modify "$new" to suit your needs.
new="${new//./ }"
# Only rename if changed.
if [ "$new" != "$old" ]; then
mv -vi "$dir/$old$ext" "$dir/$new$ext" || exit $?
fi
done
exit $?
If you save the above as
find-rename, you can then run e.g.
Hope this helps.