Exercise 0.4: Moving and Renaming
Organizing Your Files
Purpose
As you work on projects, you will constantly need to reorganize your work. Files need to be renamed for clarity, and moved into different directories to keep your project tidy. This exercise covers the commands used for moving and renaming files and directories.
What You’ll Accomplish
By the end of this exercise, you will have successfully:
- Renamed a file using the command line.
- Moved a file into a different directory.
- Understood how a single command can often perform both actions.
The Dual-Purpose Command
On macOS and Linux, a single command, mv (move), is used for both renaming and moving. The command’s behavior depends on its last argument:
- If the last argument is an existing directory,
mvmoves the source file/folder into it. - If the last argument is a new name,
mvrenames the source file/folder.
Windows uses separate commands for these actions, which can be clearer for beginners.
Your Task 1: Rename a File
First, let’s create a file and then change its name.
- Navigate to your
cli-practicedirectory. - Create a new file. Let’s call it
draft.txt. - Now, use the appropriate command for your OS to rename
draft.txttofinal.txt.
Use the mv command. The syntax is mv <old_name> <new_name>.
touch draft.txt
mv draft.txt final.txt
lsUse the Rename-Item cmdlet. The syntax is Rename-Item -Path <old_name> -NewName <new_name>.
New-Item draft.txt
Rename-Item -Path draft.txt -NewName final.txt
lsUse the ren (or rename) command. The syntax is ren <old_name> <new_name>.
echo. > draft.txt
ren draft.txt final.txt
dirAfter running the commands, you should see final.txt in your directory, and draft.txt will be gone.
Your Task 2: Move a File
Now let’s move a file into a directory.
- While still in your
cli-practicedirectory, create a new subdirectory calledarchive. - Create a new file to be moved, called
report.docx. - Use the appropriate command to move
report.docxinto thearchivedirectory.
Use the mv command again. The syntax is mv <file_to_move> <destination_directory>.
mkdir archive
touch report.docx
mv report.docx archive/
ls
ls archiveUse the Move-Item cmdlet. The syntax is Move-Item -Path <file_to_move> -Destination <destination_directory>.
mkdir archive
New-Item report.docx
Move-Item -Path report.docx -Destination archive/
ls
ls archiveUse the move command. The syntax is move <file_to_move> <destination_directory>.
mkdir archive
echo. > report.docx
move report.docx archive\
dir
dir archiveAfter running the commands, you will see that report.docx is no longer in cli-practice, but is now inside archive.
Reflect and Review
In your Microsoft Teams Student Notebook, answer the following:
- On macOS/Linux, what is the single command used for both renaming and moving?
- On Windows, what are the two separate commands for renaming and moving?
- If you wanted to rename a directory from
stufftoimportant-stuff, what command would you use on your OS?