How to rename a file inside a folder using a shell command?

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).


Solution 1:

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.

Solution 2:

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
popd

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:

D=/some/long/path
mv "$D/file1" "$D/file2"

Solution 3:

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 -

Solution 4:

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

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