How to rename a file in linux

A guide on How to rename a file in linux

There are two main ways to rename files in Linux: the mv command and the rename command. Both offer different functionalities.

Using the mv command

The mv (move) command is a versatile tool that can be used to both move and rename files. Here’s how to use it for renaming:

  1. Open your terminal.

  2. Navigate to the directory containing the file you want to rename using the cd command.

  3. Use the following syntax:

    Bash
    mv old_file_name new_file_name
    

    Replace old_file_name with the current name of the file and new_file_name with the desired new name.

    For example, to rename a file called report.txt to report_final.txt, you would use:

    Bash
    mv report.txt report_final.txt
    

Tips for using mv

  • Use the -v flag with mv for a verbose output, which shows what is being renamed.

  • Use the -i flag to enable interactive mode. This prompts you for confirmation before renaming the file, especially useful when dealing with important files.

  • While mv can rename a single file at a time, you can combine it with loops for batch renaming. Refer to online resources for scripting techniques with mv.

Using the rename command

The rename command offers more flexibility for renaming multiple files based on patterns. It’s not pre-installed on all systems, so you might need to check with command -v rename to see if it’s available. If not, you can usually install it using your package manager.

Here’s the basic syntax for rename:

Bash
rename 's/pattern/replacement/g' files
  • s/pattern/replacement/g: This part defines the renaming rule.
    • pattern: The text you want to replace in the filename.
    • replacement: The text that will replace the pattern.
    • g: This flag ensures all occurrences of the pattern are replaced.

For example, to rename all .jpg files to .png in the current directory, you would use:

Bash
rename 's/\.jpg/\.png/g' *.jpg

Important Note: Be cautious when using rename with wildcards, as it can potentially affect unintended files. It’s recommended to test on a limited set of files first.

By following these steps and understanding the functionalities of mv and rename, you can effectively rename files in Linux!