How to rename a file inside a folder using a shell command?
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 )
Related videos on Youtube
Leonid Shevtsov
Ruby, Javascript, React, React Native, Golang, Elixir, Clojure developer. Personal site: https://leonid.shevtsov.me Github: https://github.com/leonid-shevtsov
Updated on September 18, 2022Comments
-
Leonid Shevtsov over 1 year
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).
-
slhck over 11 yearsBeware that the last approach breaks when the path has a space, beter quote it.
-
Alex over 11 years@slhck ALL of the approaches break if you have spaces.
-
slhck over 11 yearsNo, if you type them correctly they won't. Only the variable when expanded will look like multiple arguments to mv
-
Alex over 11 years@slhck there you go.