Reputation: 305
The problem is well-known yet I cannot find a solution: I wish to rename directories and files, replacing the spaces by underscores. The below code does not work, for some unclear reason. This is in bash on Solaris 11.
find $BASEDIR -type d |grep ' ' | awk '{print "\"" $0 "\""}' >$TMPFIL
cat $TMPFIL | while read FILNAM ; do
F2=$(echo $FILNAM | sed -e 's/ /_/g' -e 's/\"//g')
CMD="mv "$FILNAM" "$F2
echo "Will execute: "$CMD
$CMD
done
Output looks like
Will execute:
mv "/opt/pakket/smbdata/INTSCAN/ipmdata/Errors/Herstart 2015-01-07" /opt/pakket/smbdata/INTSCAN/ipmdata/Errors/Herstart_2015-01-07
mv: /opt/pakket/smbdata/INTSCAN/ipmdata/Errors/Herstart_2015-01-07 not found
it complains about not finding the second argument. When I copy and paste the command it generates, and launch it "manually", everything works fine, though.
Upvotes: 1
Views: 108
Reputation: 46833
This should do:
find /path/to/dir -depth -name '*[[:space:]]*' -execdir bash -c 'echo mv "$0" "${0//[[:space:]]/_}"' {} \;
This will not rename anything, only show the commands that will be executed. Remove the echo
in front of mv
to actually perform the renaming.
If your find
doesn't support -execdir
(which seems to be the case on your Solaris), this should do:
find -depth -name '*[[:space:]]*' -exec bash -c 'd=${0%/*} b=${0##*/}; echo mv "$d/$b" "$d/${b//[[:space:]]/_}"' {} \;
Upvotes: 2