Linux rename Command Tutorial for Beginners (with Examples)

linux rename command tutorial for beginners with

If you work with files on the command line in Linux, renaming files is one of the most frequent tasks you may find yourself involved in. We’ve already discussed the mv command that lets you do this. And here, in this tutorial, we will discuss another such tool, dubbed rename.

But before we start with that, it’s worth mentioning that all examples in this article have been tested on an Ubuntu 18.04 LTS machine.

Linux rename command

As the name suggests, the rename command in Linux allows you to rename files. Following is its syntax:

rename [options] expression replacement file...

And here’s how the tool’s man page explains it:

rename will rename the specified files by replacing the first occurrence of expression in their name by replacement.

Note that if you don’t have the rename command installed, you can get it using the following command:

sudo apt install rename

Following are some Q&A-styled examples that should give you a better idea on how the rename command works.

Q1. How to use rename command?

Basic usage isn’t exactly straight forward, I must say, but it’s not difficult to understand. Let’s say you have a file named ‘test.txt’ and you want to rename it to ‘new.txt’. Then here’s how you use the rename command to do this.

rename 's/test/new/' test.txt

By default, the rename command just renames the file which is passed as input, even if it’s a symbolic link. However, if you want the tool to not rename symbolic links, but act on their targets instead, then use the -s command line option.

So if symlink.txt is a symbolic link that points to root.txt, then the following command will make sure the rename operation happens for root.txt:

rename -s 's/root/new/' symlink.txt

Q3. How to make a dry run with rename?

Suppose you only want to see the final change that’ll happen with a rename command, without actually carrying it out, then use the -n command line option. For example, the following command:

rename -n 's/new/test/' new.txt

produced the following output:

rename(new.txt, test.txt)

but didn’t actually rename new.txt to test.txt.

Q4. How rename handles overwriting of files?

By default, the rename command doesn’t perform the operation if it involves overwriting an existing file. However, you can force the tool to overwrite using the -f command line option.

For example, the following command:

rename 's/new/test/' new.txt

produced the following output:

new.txt not renamed: test.txt already exists

But when the -f command was used:

rename -f 's/new/test/' new.txt

The operation completed smoothly and test.txt got overwritten.

Conclusion

The rename command doesn’t offer too many options, and we’ve already discussed some of the main ones here. After you’re done practicing these, head to the tool’s man page to learn more about it.

نوشته های مشابه