0

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)

  • Hi ascendants and welcome to SE. In order to signal to others in the Community that your question received a satisfactory answer, do not forget to mark your favorite accepted answer with a green check mark. Cheers. – Cbhihe May 12 at 6:19
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.

| improve this answer | |
  • Thank you! This is a nice way without aliasing. – ascendants May 11 at 23:01
2

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
| improve this answer | |
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
| improve this answer | |
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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.