I have this in a working script that I delivered. It is written as a function, but you would call it
d_swap lfile rfile
GNU mv has -b and -T. You can handle directories using the -T switch.
Quotation marks are for filenames with spaces.
This is a bit verbose, but I have used it many times with both files and directories. There may be times when you want to rename a file with the name specified in the directory, but this is not handled by this function.
This is not very effective if all you want to do is rename the files (leaving them where they are), which is best done using a shell variable.
d_swap() { test $# -eq 2 || return 2 test -e "$1" || return 3 test -e "$2" || return 3 if [ -f "$1" -a -f "$2" ] then mv -b "$1" "$2" && mv "$2"~ "$1" return 0 fi if [ -d "$1" -a -d "$2" ] then mv -T -b "$1" "$2" && mv -T "$2"~ "$1" return 0 fi return 4 }
This function will rename files. It uses the name temp (it puts a dot “.” Before the name) just in case the files / directories are in the same directory, which usually happens.
d_swapnames() { test $# -eq 2 || return 2 test -e "$1" || return 3 test -e "$2" || return 3 local lname="$(basename "$1")" local rname="$(basename "$2")" ( cd "$(dirname "$1")" && mv -T "$lname" ".${rname}" ) && \ ( cd "$(dirname "$2")" && mv -T "$rname" "$lname" ) && \ ( cd "$(dirname "$1")" && mv -T ".${rname}" "$rname" ) }
It is much faster (no copying, just renaming). It is even uglier. And he will rename anything: files, directories, channels, devices.
user3786383 Jun 28 '14 at 17:59 2014-06-28 17:59
source share