Skip to content

Instantly share code, notes, and snippets.

@premek
Last active March 5, 2024 17:43
Show Gist options
  • Save premek/6e70446cfc913d3c929d7cdbfe896fef to your computer and use it in GitHub Desktop.
Save premek/6e70446cfc913d3c929d7cdbfe896fef to your computer and use it in GitHub Desktop.
Rename files in linux / bash using mv command without typing the full name two times
# Put this function to your .bashrc file.
# Usage: mv oldfilename
# If you call mv without the second parameter it will prompt you to edit the filename on command line.
# Original mv is called when it's called with more than one argument.
# It's useful when you want to change just a few letters in a long name.
#
# Also see:
# - imv from renameutils
# - Ctrl-W Ctrl-Y Ctrl-Y (cut last word, paste, paste)
function mv() {
if [ "$#" -ne 1 ] || [ ! -e "$1" ]; then
command mv "$@"
return
fi
read -ei "$1" newfilename
command mv -v -- "$1" "$newfilename"
}
@zouhair
Copy link

zouhair commented May 4, 2020

There are even more flexible ways (in bash, at least), for example (here renaming .txt to .json):

$ touch config.txt
$ mv config.txt !#:1:s/txt/json

This one eludes me, care to explain how it works?

@christian-oudard
Copy link

I would recommend adding --interactive to the mv commands in the script. As it is now, it is possible to overwrite existing files with no confirmation using this script.

@thecatvoid
Copy link

With the fish shell, you can type Alt-E to edit any command line in your favorite editor where you likely already know shortcuts for copying, pasting and modifying. The great thing is that is a general solution that works for any command line edits.

In bash it is C-x C-e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment