function despace()
{
while IFS='' read FILE
do
NEWFILE=`echo "$FILE" | sed -e 's/ /_/g'`
if [ "$FILE" = "$NEWFILE" ]
then
echo "No spaces detected in [$FILE]"
continue
fi
if [ -e "$NEWFILE" ]
then
echo "$NEWFILE already exists, not going to overwite it"
else
echo "Renaming [$FILE] to [$NEWFILE]"
mv "$FILE" "$NEWFILE"
fi
done
}
$ ls * | despace
Renaming [CT.SABR test 5.1.dcm] to [CT.SABR_test_5.1.dcm]
Renaming [CT.SABR test 5.10.dcm] to [CT.SABR_test_5.10.dcm]
Renaming [CT.SABR test 5.100.dcm] to [CT.SABR_test_5.100.dcm]
If a file by the name we're changing to already exists, it will not get over-written:
$ ls * | despace
Renaming [CT.SABR_test_5.1.dcm] to [CT.SABR_test_5.1.dcm]
CT.SABR_test_5.1.dcm already exists, not going to overwite it
The IFS='' is needed to catch trailing spaces on filenames (I know, no sane person would do that, but included for the sake of completeness). If you pass it filenames without spaces, it tells you and skips them.
No comments:
Post a Comment