How to rename directory and file in linux/unix

Renaming directories and files is one of the most commonly used functions of linux/unix.

So, how do we use command-line tools to rename directories or files?

The answer is: linux mv command.


mv [options] oldFileName newFileName
mv [options] oldDirectoryName newDirectoryName


rename file

In the following example, we will use the mv command to rename the file.

➜ mv oldFileName.txt newFileName.txt

In the above example, we use the mv command to rename a single file.

So, how to batch rename rule files?

At this time, we need to combine mv and awk commands to rename files in batches.

Next, we create five files [1-5].log, we use mv and awk to batch rename the five files to file_[1-5].log.

Create five files in batch:

➜ touch {1..5}.log

Rename files in batch:

➜ ls *.log | awk '{system("mv "$0" file_"$0"")}'

rename directory

In the following example, we use the mv command to rename the directory.

➜ mv oldDirectoryName newDirectoryName

Similarly, we can also use the combination of awk and mv commands to rename the rule directory in batches.

➜  mkdir {1..5}_d
➜  ls -d */
1_d/              2_d/              3_d/              4_d/              5_d/              newDirectoryName/
➜  ls | grep "_d" | awk '{system("mv "$0" dir_"$0" ")}'
➜  ls -d */
dir_1_d/          dir_2_d/          dir_3_d/          dir_4_d/          dir_5_d/          newDirectoryName/

Add a Comment

Your email address will not be published. Required fields are marked *