In this episode we will be continuing on the from episode 2 where we covered copying files, we now take a look at moving files. The good news is that these two different operations are very similar but just use different commands.
To move files or directories you will need the mv
command, short for "move". This command just like the cp
command, takes 2 arguments, the first being a path to the item you want to move (the source) and the latter being another path where you want the file or files to ending up (the destination).
Example of moving a file named "file-v1.txt" to the same directory called "file-v2.txt". Essentially we are just renaming the file.
mv file-v1.txt file-v2.txt
Example of moving a file to a child directory whilst renaming the file
mv my-file.txt ./child/my-better-file.txt
Example of moving a file to a child directory
mv my-file.txt ./child/
Example of moving a file to a parent directory whilst renaming the file
mv my-file.txt ../my-better-file.txt
Example of moving a file to a parent directory
mv my-file.txt ../
Moving multiple files is very similar to moving a single file. You use the same command mv
and also with 2 arguments. However for the first argument you can provide a regular expression that matches a certain pattern. For example you may want to move all the CSV files in one directory into another directory. A regular expression is a means to express a pattern that if expanded would list potentially many paths. However for brevity this will not be covered in this episode.
Example of moving all CSV files in the present directory to another directory
mv *.csv ../sibling/
Another way of moving multiple files without the need for regular expressions is to simply list them all out as arguments to the mv
command. All arguments will be considered as files that need moving except the last argument which is the destination directory where the files will be moved to.
Example of moving the listed files "1.csv" and "2.csv" in the present directory to another directory
mv 1.csv 2.csv ../sibling/
Another common scenario you will come across is wanting to move a directory and all the containing files and directories within it. Unlike the cp
command you do not need to pass the recursive flag -r
to acheive this. This is because the command just renames the directory it doesn't actually need to move any of its contents.
Directory structure before our move command
.
├── overview.txt
└── project1
├── assets
│ └── image.png
└── file1.txt
Example command to move project1 directory to project2
mv project1 project2
Directory structure after our move command
.
├── overview.txt
└── project2
├── assets
│ └── image.png
└── file1.txt
You should now be able to move files and directories on the command line. In the next episode we will cover how to delete files. The good news is that like the cp
and mv
commands, removing files is very similar.