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

8

2

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

Leonid Shevtsov

Posted 2012-10-12T15:33:27.330

Reputation: 790

Answers

11

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.

Tamara Wijsman

Posted 2012-10-12T15:33:27.330

Reputation: 54 163

Oh my, this opens so much possibilities. Thanks! – Leonid Shevtsov – 2012-10-12T15:58:07.870

5

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"

tylerl

Posted 2012-10-12T15:33:27.330

Reputation: 2 064

Beware that the last approach breaks when the path has a space, beter quote it. – slhck – 2012-10-12T15:57:29.680

@slhck ALL of the approaches break if you have spaces. – tylerl – 2012-10-12T15:58:41.703

1No, if you type them correctly they won't. Only the variable when expanded will look like multiple arguments to mv – slhck – 2012-10-12T16:09:34.530

@slhck there you go. – tylerl – 2012-10-12T16:50:31.973

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 -

Yedric

Posted 2012-10-12T15:33:27.330

Reputation: 649

1

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

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

Keith Wolters

Posted 2012-10-12T15:33:27.330

Reputation: 131