Objectives & prerequisites
- Demonstrate how to rename and move files and directories.
- Demonstrate how to handle files and directories with names containing spaces.
None.
Overview
Use mv to move files and directories into another directory.
You can also use this command to rename files and directories.
Moving files and directories
Moving a file into another directory
sarah@laptop ~/Downloads$ mv puppies.jpg ~/images/animals
sarah@laptop ~/Downloads$→ The above command moves the file ~/Downloads/puppies.jpg into the ~/images/animals directory.
Moving a directory into another directory
sarah@laptop ~/Downloads$ mv movies ~/mystuff
sarah@laptop ~/Downloads$→ The above command moves the directory ~/Downloads/movies and all of its contents into the ~/mystuff directory.
Renaming files and directories
Renaming a file and keeping it in the same directory
sarah@laptop ~/images/animals$ mv DCIM_3493.jpg ~/images/animals/rex.jpg
sarah@laptop ~/images/animals$→ The above command renames the file DCIM_3493.jpg to rex.jpg.
Renaming a directory
sarah@laptop ~/images/animals$ mv doggs dogs
sarah@laptop ~/images/animals$→ The above command renames the directory ~/images/animals/doggs to ~/images/animals/dogs
Moving and renaming at the same time
Moving a file into another directory and renaming it
sarah@laptop ~/Downloads$ mv puppies.jpg ~/images/animals/dogs/cute_puppies.jpg
sarah@laptop ~/Downloads$→ The above command moves the file ~/Downloads/puppies.jpg into the ~/images/animals/dogs directory, and renames the file to cute_puppies.jpg.
Directories with spaces in their name
There are two ways to work with directories that have spaces in their name:
Use single or double quotes
sarah@laptop:~/Documents$ mv "Updated reports" updated_reportsThe above command renames the Updated reports directory to updated_reports
Use backslash to escape each whitespace character
sarah@laptop:~/Documents$ mv Updated\ reports updated_reportsBoth methods are equivalent; feel free to use the one you are most comfortable with.
Activity
What does the following command do?
sarah@laptop ~/Downloads/movies/French/action$ mv ../../movies ~/Entertainment
It moves the directory ~/Downloads/movies into the directory ~/Entertainment.
Activity
How would you write the same command used in the previous activity, but using absolute paths instead?
sarah@laptop ~/Downloads/movies/French/action$ mv /home/sarah/Downloads/movies ~/Entertainmentor
sarah@laptop ~/Downloads/movies/French/action$ mv /home/sarah/Downloads/movies /home/sarah/Entertainment
Remember:
The tilde represents the absolute path to your home directory, so ~ and /home/YOUR-USERNAME are considered identical.
Summary
- Use
mvto move files and directories into another directory. - Also use
mvto rename files and directories. - If the directory name contains whitespaces, wrap the name in quotes or escape each whitespace character with a backslash (
\)