1

I find myself frequently needing to rename different files with mv that are in deep directories:

mv /a/long/path/to/a/file.txt /a/long/path/to/a/file.txt.bak

But I don't want to retype the full path name. Is there a quick shorthand or alias that I could use? I.e.:

$ mv /a/long/path/to/a/file.txt file.txt.bak
$ ls /a/long/path/to/a/file.txt.bak
a/long/path/to/a/file.txt.bak

(note: this is for straightforward, single file renames in different directories at different times, not for mass-renames)

ascendants
  • 275
  • 2
  • 10

4 Answers4

5

Use a brace expansion:

mv /a/long/path/to/a/file.txt{,.bak}

This renames /a/long/path/to/a/file.txt with an empty suffix to /a/long/path/to/a/file.txt with suffix .bak.

Freddy
  • 25,565
3

Although I'd probably use brace expansion, as illustrated in Freddy's answer, in both bash and zsh one could use interactive history expansion, with designator #$ to refer to the last word typed so far on the current line:

mv /a/long/path/to/a/file.txt !#$.bak
steeldriver
  • 81,074
0

This may be a basic question, but I hadn't found a existing question/answer for this. The simple solution I made was a function in ~./bash_functions**:

#/home/user/.bash_functions

function mv-rn() {
  mv $1 $(dirname $1)/${2}
}

So that now:

$ mv-rn /a/long/path/to/a/file.txt file.txt.bak
$ ls /a/long/path/to/a/file.txt.bak
a/long/path/to/a/file.txt.bak

(**note that you must have this in your ~/.bashrc for the above function to be recognized as an alias):

# Function definitions.
if [ -f ~/.bash_functions ]; then
    . ~/.bash_functions
fi
ascendants
  • 275
  • 2
  • 10
0
(cd /a/long/path/to/a && mv file.txt file.txt.bak)

The && ensures that the mv will be executed only if the cd succeeds. The parentheses mean that the commands will execute in a subshell, so the cd will not change your existing shell's working directory.

Mark Plotnick
  • 25,413
  • 3
  • 64
  • 82