I have a file at some/long/path/to/file/myfiel.txt.

I want to rename it to some/long/path/to/file/myfile.txt.

Currently I do it by mv some/long/path/to/file/myfiel.txt some/long/path/to/file/myfile.txt, but typing the path twice isn't terribly effective (even with tab completion).

How can I do this faster? (I think I can write a function to change the filename segment only, but that's plan B).


To do this in a single command, you can simply do this:

mv some/long/path/to/file/{myfiel.txt,myfile.txt}

Which is an example for the full file name, given that it's a typo you can do something like:

mv some/long/path/to/file/myfi{el,le}.txt

Both will expand to the full command, these are called brace expansions. They are supported by zsh.

  • Oh my, this opens so much possibilities. Thanks! – Leonid Shevtsov Oct 12 '12 at 15:58

Here are several options:

Change to the directory:

cd /home/long/path
mv file1 file2
cd -

Change directories using the directory stack:

pushd /some/long/path
mv file1 file2

Change to the directory using a subshell:

  cd /some/long/path
  mv file1 file2
)   # no need to change back

Use brace expansion:

mv /some/long/path/{file1,file2}

Use a variable:

mv "$D/file1" "$D/file2"
  • Beware that the last approach breaks when the path has a space, beter quote it. – slhck Oct 12 '12 at 15:57
  • @slhck ALL of the approaches break if you have spaces. – tylerl Oct 12 '12 at 15:58
  • 1
    No, if you type them correctly they won't. Only the variable when expanded will look like multiple arguments to mv – slhck Oct 12 '12 at 16:09
  • @slhck there you go. – tylerl Oct 12 '12 at 16:50

Change to the directory, move the file, and change back to the previous directory; like so:

cd some/long/path/to/file
mv myfiel.txt myfile.txt
cd -

When I use the subshell method I would tend to do it on one line like so

(cd /some/long/path ; mv myfiel myfile )

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.