Как переименовать файл в ubuntu через терминал
Перейти к содержимому

Как переименовать файл в ubuntu через терминал

  • автор:

How to rename a file in Terminal? [duplicate]

How do I rename my_static to static and remove static (2)?

383 5 5 silver badges 12 12 bronze badges
asked Apr 12, 2013 at 18:23
user2054574 user2054574
2,761 2 2 gold badges 13 13 silver badges 4 4 bronze badges

2 Answers 2

mv "old location" "new location" mv /home/user/my_static /home/user/static 

That command is used for moving and renaming files and directories.

answered Apr 12, 2013 at 18:24
4,006 1 1 gold badge 13 13 silver badges 4 4 bronze badges

For experienced users this comment is superfluous, but it’s worth noting this will also unlink (remove) the original static directory.

Apr 12, 2013 at 18:27

Sometime you may want to back the file up, like a config file, use cp /home/file1 /home/file1.bak you will have 2 files.

Apr 12, 2013 at 18:46

A simple way to rename files and folders is with the mv command (shortened from “move”). Its primary purpose is moving files and folders, but it can also rename them since the act of renaming a file is interpreted by the filesystem as moving it from one name to another.

mv (option) file1.ext file2.ext 

where “file1.ext” is the “old” name of the file, and “file2.ext” the new name.

And to remove, you can use the command:

rm -f filename 

How to Rename Files in Ubuntu

Rename files in Ubuntu command line

Renaming a file is easy when you are using a mouse in a graphical explorer. But if you are new to the Linux command line and stuck to the terminal, things could be overwhelming.

In the terminal, you can use the mv command to rename a file in Ubuntu:

mv OLD_NAME NEW_NAME

Replace ‘OLD_NAME’ and ‘NEW_NAME’ with the current file name and the name that you wish to rename it with, respectively.

You can rename individual files in this way. There are also ways to rename multiple files in the command line.

I’ll go over these things in a bit more detail here.

Rename a single file

To rename a file, the mv command is used. The mv command is for moving (or more like cut-paste kind of operations) files from one location to another. But if you use the mv command on a file in the same location, it renames the file instead.

Below is the syntax for mv command:

mv OLD_NAME NEW_NAME

Let us take a look at a simple example. Here, I rename pls_rename.txt file to renamed_it.txt .

$ ls *.txt pls_rename.txt $ mv -v pls_rename.txt renamed_it.txt renamed 'pls_rename.txt' -> 'renamed_it.txt' $ ls *.txt renamed_it.txt

Renaming multiple files

The mv command is great, but it can not rename multiple files at once. For example, you can not issue a command like this:

$ ls *.txt image_1.txt image_2.txt image_3.txt image_4.txt image_4.txt $ mv -v *.txt *.jpeg zsh: no matches found: *.jpeg

So what do you do when you have multiple files and want to rename them in Ubuntu command line?

You can try using the find-exec command combination but it gets complicated. A simpler option is using the rename command.

Unfortunately, it is not pre-installed in Ubuntu. Use the apt command to install it:

sudo apt install rename

The rename command uses regular expression pattern matching to rename files. Below is its syntax:

rename PERL-REGEX FILES

The term ‘PERL-REGEX’ in the syntax means that the regular expression it receives must be in Perl’s syntax.

Let us try to rename the ‘image_*.txt’ files to their correct extension. Since the only thing you want to do is replace ‘.txt’ with ‘.jpeg’, you can use substitution with regular expressions like this:

$ rename -v 's/.txt/.jpeg/' *.txt image_1.txt renamed as image_1.jpeg image_2.txt renamed as image_2.jpeg image_3.txt renamed as image_3.jpeg image_4.txt renamed as image_4.jpeg image_5.txt renamed as image_5.jpeg

Regular expressions are powerful. Try renaming a file with lowercase characters into uppercase characters, DOS-style :p

$ ls i_am_not_screaming maybe_i_am_screaming who_knows $ rename -v 'y/a-z/A-Z/' * i_am_not_screaming renamed as I_AM_NOT_SCREAMING maybe_i_am_screaming renamed as MAYBE_I_AM_SCREAMING who_knows renamed as WHO_KNOWS $ ls I_AM_NOT_SCREAMING MAYBE_I_AM_SCREAMING WHO_KNOWS

Tips on preventing mistakes while bulk renaming files

This is an example, and hence I only created 5 files for demonstration.

But in real life, you might have upwards of hundreds of files. Since, you and I, both are humans, we tend to make mistakes, especially with regular expressions.

For that to not be a scathing issue, there exists a life-saving option. That is the —nono option.

When you use this option, the rename command will show what the changes might look like, instead of actually renaming files. Very handy!

If you are aware of the term ‘dry run’, this is essentially that.

Let us take a look at an example of renaming all ‘image_*.jpeg’ files back to the ‘.txt’ extension:

$ rename --nono 's/.jpeg/.txt/' *.jpeg rename(image_1.jpeg, image_1.txt) rename(image_2.jpeg, image_2.txt) rename(image_3.jpeg, image_3.txt) rename(image_4.jpeg, image_4.txt) rename(image_5.jpeg, image_5.txt) $ ls *.jpeg image_1.txt image_2.txt image_3.txt image_4.txt image_5.txt

As you can see, the files have not been renamed. It was only demonstrated what might occur if I were to run the command.

Conclusion

This article covers the steps to rename individual files with the mv command and multiple files with the rename command.

Most people are usually familiar with the mv command but not rename. I hope you liked learning about the rename command in Ubuntu. Bookmark this site and visit regularly for more Ubuntu tutorials.

Переименование файла или папки

Как и другие менеджеры файлов, приложение Файлы позволяет переименовать файл или папку.

Чтобы переименовать файл или папку:

  1. Нажмите на объект правой кнопкой и выберите Переименовать или выберите файл и нажмите клавишу F2 .
  2. Наберите новое имя и нажмите Enter или кнопку Переименовать .

Можно также переименовать файл из окна его свойств .

При переименовании файла выделяется только начало его имени, без расширения (части после . ). Расширение показывает тип файла (например, file.pdf — это документ PDF), и менять его обычно нет необходимости. Если нужно изменить и расширение, выделите имя файла целиком и измените его.

Если вы переименовали не тот файл, или дали ему неправильное имя, можно отменить переименование. Для этого немедленно нажмите кнопку меню в панели инструментов и выберите Переименовать или нажмите Ctrl + Z , чтобы вернуть прежнее имя файла.

Символы, допустимые в именах файлов

В именах файлов можно использовать любые символы, кроме / (слеш). Однако на некоторых устройствах используется файловая система с дополнительными ограничениями на имена файлов. Поэтому рекомендуется избегать использования следующих символов в именах файлов: | , \ , ? , * , < , " , : , >, / .

Если имя файла начинается с символа . , то этот файл будет скрытым в менеджере файлов.

Типичные проблемы

Имя файла уже используется

Нельзя поместить два файла с одинаковым именем в одну и ту же папку. Менеджер файлов не позволит переименовать файл, если такое имя уже существует в этой папке.

Имена файлов и папок чувствительны к регистру символов, поэтому File.txt и FILE.txt — это два разных имени. Использовать имена файлов, различающиеся только регистром символов разрешается, но не рекомендуется.

Слишком длинное имя файла

В некоторых файловых системах имена файлов не могут содержать более 255 символов. Это ограничение в 255 символов включает в себя как собственно имя файла, так и путь к файлу (например, /home/wanda/Documents/work/business-proposals/… ), поэтому по возможности следует избегать длинных имён файлов и папок.

Команда переименования неактивна

Если команда Переименовать недоступна, значит у вас нет прав на переименование файла. Следует соблюдать осторожность при переименовании подобных файлов, так как переименование некоторых защищённых файлов может привести к нестабильности системы. Подробнее смотрите Настройка прав доступа к файлам .

Дополнительная информация

You can choose the displayed language by adding a language suffix to the web address so it ends with e.g. .html.en or .html.de.
If the web address has no language suffix, the preferred language specified in your web browser’s settings is used. For your convenience:
[ Change to English Language | Change to Browser’s Preferred Language ]

The material in this document is available under a free license, see Legal for details.
For information on contributing see the Ubuntu Documentation Team wiki page. To report errors in this documentation, file a bug.

How to Rename Files in Linux

Linux provides several options for renaming files using the GUI or multiple dedicated terminal commands. Renaming individual files is straightforward, but it can be challenging to rename multiple files simultaneously.

In this tutorial, we will go over different commands you can use in the Linux terminal to rename files in Linux.

How to rename files in Linux

  • A system running a Linux distribution.
  • An account with sudo privileges.
  • Access to the terminal window/command line.
  • Access to a text editor, such as Vim or nano.

Rename Files with the mv Command

The Linux mv (move) command moves or renames files and directories through the terminal. The command’s effects depend on the provided destination:

  • If you specify a directory as the destination when using the mv command, the source file moves to that directory.
  • If the destination is another file name, the mv command renames the source file to that name instead.

Therefore, to rename files with the mv command, provide a new file name and, optionally, a destination directory.

Note: Learn more about using the mv command in our guide to moving directories in Linux.

mv Command Syntax and Options

The mv command uses the following syntax:

mv [options] [source] [destination]

The command has several options to control overwrite and display behavior. Some options are in the table below:

Option Description
-f
—force
Overwrites without prompting.
-i
—interactive
Prompts before overwriting.
-n
—no-clobber
Avoids overwriting an existing file.
-v
—verbose
Shows a verbose output.

Use the man command to view all the available options.

mv Command Examples

The mv command is simple to use for file renaming. Combining it with other commands and with Bash scripts enables advanced renaming operations.

Below are several examples showcasing how to use mv to rename files.

1. Rename a File

The mv command with its default syntax allows you to rename a single file. For example, to rename example1.txt into example2.txt, use:

mv example1.txt example2.pdf

The command does not show an output. Use -v option with the command or the ls command to check the name change before and after executing the mv command:

ls -l

Renaming a single file using the mv command

Use this method to change a single file’s extension or to rename a file.

2. Move and Rename a File

Provide the destination path and new file name to move and rename a file. For example:

mv dir1/example1.txt dir2/example2.txt

The command moves the file from dir1 to dir2 and renames it from example1.txt to example2.txt.

3. Prompt on Overwrite

To avoid accidental overwrites, add the -i option to enter interactive mode:

mv -i example1 example2

mv -i terminal output overwrite

If the file exists, the command prompts asking whether to overwrite the file. Use this mode to avoid losing a file when renaming.

4. Rename Multiple Files Command

Use the find command to select multiple files with a similar name, and then use the mv command to rename them.

Warning: Before making bulk modifications to files, create backup copies of critical files to preserve original names. Renaming files is irreversible.

find . -depth -name "[current pattern]" -exec sh -c 'f="<>"; mv -- "$f" "$[new pattern]"' \;

The find command searches through nested directories and defines the [current pattern] as the search parameter. Next, the -exec option executes the mv command on files matching the pattern. Lastly, the changes apply according to the [new pattern] .

For instance, to change the .txt extension to .pdf for multiple files, use the following command:

find . -depth -name "*.txt" -exec sh -c 'f="<>"; mv -- "$f" "$.pdf"' \;

Renaming multiple files using the find and mv commands

The command changes the file extension from .txt to .pdf for all files in the current directory. Use this command to perform complex batch renaming

5. Rename Multiple Files Bash Script

Instead of the find command, you can use the mv command as a part of a Bash for loop to rename multiple files.

Using the same example as in the section above, do the following:

1. Create and open a Bash script file via a text editor such as nano:

nano rename_files.sh

2. Add the following lines to the script:

#!/bin/bash for f in *.txt; do mv -- "$f" "$.pdf" done

Each line does the following:

  • The first line is the shebang, indicating it’s a Bash script.
  • The second line begins a for loop to iterate through files in the current directory ending with .txt.
  • The third line uses the mv command on each file found to replace the .txt extension with .pdf.
  • The last line ends the loop segment.

3. Press Ctrl+X, type Y, and press Enter to save the changes to the script and exit.

4. Use the sh command to execute the script:

sh rename_files.sh

Renaming multiple files using a bash script

Note: Learn how to compare two files using the diff command.

Rename Files with the rename Command

The rename command is used to rename multiple files or directories in Linux. It offers more features than the mv command but can be challenging since it requires basic knowledge of Perl expressions.

How to Install the rename Command

On many Linux distributions, the rename command is not available by default. If your system does not have the rename command, use one of the commands below (depending on the distribution):

sudo apt install rename
  • For CentOS and Fedora, use:
sudo yum install prename
sudo pacman -S rename

rename Command Syntax and Options

Perl regular expressions have three working modes: match, substitute, and translate. The rename command uses substitute and translate expressions to change file and directory names.

Substitute expressions replace a part of the file name with a different string. They use the following syntax:

rename [options] 's/[pattern]/[replacement]/' [file name]

With this syntax, the command renames the file by replacing the first occurrence of the pattern with the replacement. In the command above:

  • rename . Invokes the rename command.
  • [options] . Provides an optional argument that changes the way the command executes.
  • s . Indicates a substitute expression.
  • [pattern] . Specifies the part of the file name you want to replace.
  • [replacement] . Specifies a replacement for the part of the current filename.
  • [file name] . Defines the file you want to rename.

A translate expression translates one string of characters into another, character for character. This type of expression uses the following syntax:

rename [options] 'y/[string 1]/[string 2]/' [filename]

An example of a rename command using a translate expression:

rename 'y/abc/xyz/'

In this example, every «a» character in the filename is replaced by an «x«, every «b» by a «y«, and every «c» by a «z«.

The rename command uses the following options:

  • -a . Replaces all the file name element occurrences instead of just the first one.
  • -f . Forces an overwrite of existing files.
  • -h . Displays the help text.
  • -i . Displays a prompt before overwriting existing files.
  • -l . Replaces the last occurrence of the filename element instead of the first one.
  • -n . Performs a dry run, making no permanent changes. Best combined with the verbose output ( -v ).
  • -s . Renames the target instead of the symlink.
  • -v . Shows a verbose version of the output.
  • -V . Displays the command version.

rename Command Examples

1. Change File Extension

Using our last example, change the file extension from .txt to .pdf with:

rename -v 's/.txt/.pdf/' *.txt

Using the rename command to replace the file extension

2. Replacing a Part of a Filename

Replacing a different part of the filename follows the same syntax as the example above. To rename example1.txt, example2.txt, and example3.txt to test1.txt, test2.txt, and text3.txt, use:

rename -v 's/example/test/' *.txt

Renaming multiple files using the rename command

3. Delete a Part of a Filename

The rename option also allows you to delete a part of the filename by omitting the replacement part of the expression. For instance, if we want to shorten example into ex:

rename -v 's/ample//' *.txt

Removing a part of the file name using the rename command

4. Rename Files with Similar Names

Another use for the rename option is to rename files with similar names. For instance, if we want to rename files with example and sample in their name to test, use this command:

rename -v 's/(ex|s)ample/test/' *.txt

Renaming multiple files with similar names using the rename command

5. Rename Files Character-by-Character

The rename command also allows you to use translate expressions to rename files character-by-character. For instance, if you want to rename multiple files named example file by replacing the blank space with an underscore (_), use:

rename -v 'y/ /\_/' *.txt

Removing blank spaces from file names using the rename command

6. Convert Lowercase Characters

To convert lowercase characters in filenames into uppercase characters, use:

rename -v 'y/a-z/A-Z/' *.txt

Converting file names from lowercase to uppercase using the rename command

7. Convert Uppercase Characters

The reverse also works if we switch the order of the uppercase and lowercase characters in the expression:

rename -v 'y/A-Z/a-z/' *.TXT

Converting file names from uppercase to lowercase using the rename command

Note: Be careful when changing the character case, as this also changes the file extension.

Rename Files with GUI

The GUI is a convenient way to rename one or multiple files. To rename one or more files through the GUI, do the following:

1. Open the Files menu and navigate to the correct location.

Files location example files

2. Select a file or all the files to be renamed.

3. Press F2 to open the renaming prompt. Alternatively, right-click and choose Rename.

4a. (One file) Enter the new file name and press Rename to confirm for a single file. The prompt does not allow renaming if the chosen file name exists in the directory.

File rename GUI Ubuntu

4b. (Multiple files) Choose whether to rename the files using a template (such as appending numbers to file names) or to find and replace text in names. The menu shows a preview before renaming.

Bulk file rename GUI Ubuntu

Click Rename to confirm renaming multiple files.

After reading this tutorial, you should know how to rename files using the mv and rename commands in Linux.

Learn more about using Linux commands in our Linux Commands Cheat Sheet.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *