С помощью командной строки можно выполнять любые операции с файлами и папками. Например, их можно редактировать, копировать, перемещать или переименовывать. В данной статье мы рассмотрим именно переименования. Здесь вы узнаете, как переименовать файл или папку в командной строке Windows 10 или Windows 7.
Команда RENAME (REN)
Для переименования файлов и папок в командной строке Windows 10 или Windows 7 нужно использовать команду REN (или ее синоним RENAME). Данная команда принимает путь к файлу, который нужно переименовать, и новое название. Синтаксис команды выглядит следующим образом:
rename [<drive>:][<path>]<filename1> <filename2> ren [<drive>:][<path>]<filename1> <filename2>
[<drive>:] | Диск, на котором расположен файл или каталог, который нужно переименовать. |
[<path>] | Путь к файлу. |
<filename1> | Имя файла |
<filename2> | Новое имя для файла. |
Важные замечания:
- Команда rename позволяет использовать подстановочные знаки (* и ?). С их помощью можно переименовать сразу несколько файлов. Замененные подстановочными знаками символы будут идентичными символам из исходного имени.
- Новое имя (<filename2>) должно быть уникальным. Если такое имя уже занято, то будет выведена ошибка.
- Команду rename нельзя использовать для перемещения файлов в другую папку или на другой диск.
Примеры переименования
Для того чтобы переименовать файл в текущей папке достаточно ввести команду «ren» и указать старое и новое название. Например:
ren file.txt new_name.txt
Для переименования сразу нескольких файлов можно использовать подстановочные знаки (* и ?). Например, для того чтобы изменить расширение всех файлов с html на txt нужно выполнить следующую команду:
ren *.html *.txt
Таким же образом переименовываются и папки.
Если в названии файла или папки имеются пробелы, то такие названия нужно заключать в двойные кавычки. Например:
ren "file name.txt" "new name.txt"
При необходимости можно указать полный путь к исходному файлу, который нужно переименовать. Например, для того чтобы переименовать документ «new name.txt» в папке «d:temp» нужно выполнить следующую команду:
ren "d:tempnew name.txt" my-file.txt
Обратите внимание, если вы создаете командный файл (*.bat, *.cmd), то для корректного переименования файлов или папок с кирилличными символами, текст команд должен быть сохранен в DOS-кодировке (CP866).
Сохранить в такой кодировке можно с помощью текстового редактора Akelpad (скачать).
Посмотрите также:
- Как изменить расширение файла в Windows 7
- Как передать файл большого размера через Интернет
- Как закрепить BAT-файл на панели задач или в меню «Пуск»
- Как быстро выделить сразу все файлы в папке
- Как изменить дату создания (изменения) файла в его свойствах
Автор
Александр Степушин
Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.
Остались вопросы?
Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.
Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на Github или отредактировать документ в vim. Всё это происходит так часто, что все основные действия с файлами становится быстрее и привычнее выполнять в консоли. Рассказываем и показываем основные команды, которые помогут ускорить работу в терминале под ОС Windows.
Для начала нужно установить терминал или запустить командную строку, встроенную в Windows — для этого нажмите Win+R и введите cmd. Терминал часто встречается и прямо в редакторах кода, например, в Visual Studio Code.
Чтобы ввести команду в консоль, нужно напечатать её и нажать клавишу Enter
.
Содержимое текущей папки — dir
Выводит список файлов и папок в текущей папке.
C:content-server>dir
Том в устройстве C имеет метку SYSTEM
Серийный номер тома: 2C89-ED9D
Содержимое папки C:content-server
06.10.2020 00:41 <DIR> .
06.10.2020 00:37 <DIR> .circleci
16.07.2020 16:04 268 .editorconfig
16.07.2020 16:04 10 .eslintignore
16.07.2020 16:04 482 .eslintrc
06.10.2020 00:37 <DIR> .github
16.07.2020 16:04 77 .gitignore
06.10.2020 00:41 <DIR> assets
06.10.2020 00:41 <DIR> gulp
16.07.2020 16:10 379 gulpfile.js
16.07.2020 16:10 296 320 package-lock.json
16.07.2020 16:10 751 package.json
16.07.2020 16:04 509 README.md
Открыть файл
Чтобы открыть файл в текущей папке, введите его полное имя с расширением. Например, blog.txt или setup.exe.
Перейти в другую папку — cd
Команда cd
без аргументов выводит название текущей папки.
Перейти в папку внутри текущего каталога
C:content-server>cd assets
C:content-serverassets>
Перейти на одну папку вверх
C:content-serverassets>cd ..
C:content-server>
Перейти в папку на другом диске
c:content-server>cd /d d:/
d:>
Чтобы просто изменить диск, введите c:
или d:
Больше статей о фронтенде и работе в айти в телеграм-канале.
Создать папку — mkdir или md
Создаём пустую папку code
внутри папки html
:
d:html>mkdir code
d:html>dir
Содержимое папки d:html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:25 <DIR> code
0 файлов 0 байт
3 папок 253 389 438 976 байт свободно
Создаём несколько пустых вложенных папок — для этого записываем их через косую черту.
d:html>mkdir cssjs
d:html>dir
Том в устройстве D имеет метку DATA
Серийный номер тома: 0000-0000
Содержимое папки d:html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:25 <DIR> code
03.11.2020 19:29 <DIR> css
Создаётся папка css
, внутри которой находится папка js
. Чтобы проверить это, используем команду tree
. Она показывает дерево папок.
Удалить папку — rmdir или rd
Чтобы удалить конкретную папку в текущей, введите команду rmdir
.
d:htmlcss>rmdir js
При этом удалить можно только пустую папку. Если попытаться удалить папку, в которой что-то есть, увидим ошибку.
d:htmlcss>d:html>rmdir css
Папка не пуста.
Чтобы удалить дерево папок, используйте ключ /s
. Тогда командная строка запросит подтверждение перед тем, как удалить всё.
d:html>rmdir css /s
css, вы уверены [Y(да)/N(нет)]? y
Показать дерево папок — tree
В любом момент мы можем увидеть структуру папок. Для этого используется команда tree
.
d:html>tree
Структура папок тома DATA
Серийный номер тома: 0000-0000
D:.
├───code
└───css
└───js
Если вы хотите посмотреть содержимое всего диска, введите tree в корне нужного диска. Получится красивая анимация, а если файлов много, то ещё и немного медитативная.
Удаление файла — del или erase
Команда для удаления одного или нескольких файлов.
d:html>del blog.txt
Переименование файла — ren или rename
Последовательно вводим ren, старое и новое имя файла.
d:html>dir
Содержимое папки d:html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:59 0 blag.txt
d:html>ren blag.txt blog.txt
d:html>dir
Содержимое папки d:html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:59 0 blog.txt
Команды одной строкой
Очистить консоль — cls
Информация о системе — systeminfo
d:html>systeminfo
Имя узла: DESKTOP-6MHURG5
Название ОС: Майкрософт Windows 10 Pro
Версия ОС: 10.0.20246 Н/Д построение 20246
Изготовитель ОС: Microsoft Corporation
Параметры ОС: Изолированная рабочая станция
Сборка ОС: Multiprocessor Free
Информация о сетевых настройках — ipconfig
d:html>ipconfig
Настройка протокола IP для Windows
Адаптер Ethernet Ethernet 2:
Состояние среды. . . . . . . . : Среда передачи недоступна.
DNS-суффикс подключения . . . . . :
Список запущенных процессов — tasklist
c:>tasklist
Имя образа PID Имя сессии № сеанса Память
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 8 КБ
System 4 Services 0 2 688 КБ
Secure System 72 Services 0 23 332 КБ
…
Справка по командам — help
Команда help без аргументов выводит список всех возможных команд. help
вместе с именем команды выведет справку по этой команде.
d:html>help tree
Графическое представление структуры папок или пути.
TREE [диск:][путь] [/F] [/A]
/F Вывод имен файлов в каждой папке.
/A Использовать символы ASCII вместо символов национальных алфавитов.
В этой статье приведены не все команды и не все их возможности, но вы всегда можете воспользоваться командой help и узнать о том, что ещё может командная строка.
Как ещё ускорить работу
- 10 горячих клавиш VS Code, которые ускорят вашу работу
- Полезные команды для работы с Git
- Полезные команды для работы с Node. js
Updated: 12/05/2021 by
Below are steps on how you can rename a file, shortcut, or directory. Click one of the following links to automatically navigate to the correct operating system.
Note
You must have write or modify permissions to a file, folder, or directory to rename it. In some cases, you may need administrator privileges in the operating system to rename.
How to rename in Microsoft Windows
Windows users can rename their files and directories using one of the following methods. We’ve listed the following recommendations in what we believe to be the easiest methods of renaming a file. These methods work for most types of files, including text, photos, documents, and others.
Tip
This also works for removing spaces in a file name.
Note
Renaming a folder containing files may cause problems if that folder contains files that are required by a program. For example, if the program is looking for a folder named «data» and you rename it to «other» the program would no longer know where data files are located.
Method one
- Highlight the file or folder.
- Right-click the file with your mouse and select Rename from the menu that appears.
Tip
In Windows 11, select Show more options in the right-click menu to see the Rename option.
Method two
- Highlight the file or folder.
- Press F2 on the keyboard.
Method three
- Highlight the file or folder.
- Click File at the top of the window and select Rename from the list of available options.
Tip
File Explorer in Windows 11 does not have a file menu like previous versions of Windows. Instead, click the Rename icon in the menu bar at the top.
Method four
- Highlight the file or folder.
- Once highlighted, wait a few seconds and click the file name again. A box should appear surrounding the file or folder name, and you can rename the file.
Note
If you don’t wait long enough and click the file or folder too fast, it can open it rather than allowing you to rename it.
Renaming multiple files or folders at once
- Open Explorer.
- In Explorer, select all the files you want to rename.
- How to select or highlight multiple files and folders.
- Once the files are selected, press F2 to edit the file name and type the new name for the files. For example, typing «test» renames the files to test, test(1), test(2), test(3), etc. If you have file extensions displayed, make sure to also type the name of the file extension.
Microsoft Windows users can also rename any file using the Windows command line.
How to rename in MS-DOS and the Windows command line
MS-DOS and Windows command (CMD) line users can change the name of a file or directory using the ren or rename command. Below are examples of how this command can be used. Additional information about these commands is found by clicking the command links above.
- How to get to an MS-DOS prompt or Windows command line.
Renaming a file
The following example renames the file test.txt to hope.txt.
rename test.txt hope.txt
If the test.txt file is not located in your current directory, you must specify the file’s path as a prefix to the file name. For example, if the file is in the «computer» directory, type a command similar to the following example.
rename c:computertest.txt hope.txt
Renaming a file with a space
If a file or directory has a space, it must be surrounded with quotes. Otherwise, you get the «The syntax of the command is incorrect» error. To rename the file «computer hope.txt» to «example file.txt«, your command would resemble the following example.
rename "computer hope.txt" "example file.txt"
Renaming multiple files with one command
To rename multiple files at once, you must utilize some form of wild character. Below are examples of how this could be done.
The following example renames all the files in the current directory that end with .rtf to .txt files.
rename *.rtf *.txt
In this next example, the command renames a file with an unknown character in the file name to something that can be read. The «?» used in the following example is the wild character for an unknown character.
rename h?pe.txt hope.txt
Renaming a directory
Renaming a directory in MS-DOS is much like renaming a file. Use the ren or rename command to rename the directory. Because you cannot have a file and directory of the same name, you don’t need to worry about mistakenly renaming a file instead of a directory. The only exception is if you’re using wild characters.
Note
Renaming a directory containing files may cause problems if that directory contains files required by a program. For example, if the program is looking for a directory named «data» and you rename it to «other,» the program would no longer know where data files are located.
The following example renames the computer directory to hope.
rename computer hope
Rename the directory «computer hope» to «example directory». Whenever dealing with a file or directory with a space, it must be surrounded with quotes. Otherwise, you get the «The syntax of the command is incorrect» error.
rename "computer hope" "example directory"
Rename in a batch file
To rename files in a batch file, you can use any of the rename commands or examples shown in the MS-DOS and Windows command line section.
How to rename in macOS
Apple macOS users can rename their files and directories using one of the following methods. We’ve listed the following recommendations in what we believe to be the easiest methods of renaming a file.
First recommendation
In the macOS Finder, select the file by clicking the file once and then press return on the keyboard. After pressing return, type the new name of the file.
Second recommendation
Select the file or icon you want to rename. Click and then hover over the file name until it is highlighted. Once highlighted, this indicates the file can be renamed.
Third recommendation
Using the Terminal, you can also rename any file. See our Linux and Unix users section for steps on renaming a file using the mv command.
How to rename in the Linux and Unix command line
For detailed information about renaming files in Linux, see the Linux mv command.
How to rename in Google Chrome OS
With the Google Chrome OS on a Chromebook, you can rename your files and directories using one of the following methods. We’ve listed the following recommendations in what we believe to be the easiest methods of renaming a file.
First recommendation
Highlight the file by clicking the file once. Press Ctrl+Enter on the keyboard and then type the new name of the file.
Second recommendation
Right-click the file by pressing two fingers on the touchpad at the same time. In the right-click menu, click Rename and then type the new file name.
How to rename a document in Word or Excel
- Open the document you want to rename.
- Click File, then click Save As.
- In the Filename box, type the new name.
- Click Save. At this point, you can delete the old file or keep it as a backup.
Updated: 12/05/2021 by
Below are steps on how you can rename a file, shortcut, or directory. Click one of the following links to automatically navigate to the correct operating system.
Note
You must have write or modify permissions to a file, folder, or directory to rename it. In some cases, you may need administrator privileges in the operating system to rename.
How to rename in Microsoft Windows
Windows users can rename their files and directories using one of the following methods. We’ve listed the following recommendations in what we believe to be the easiest methods of renaming a file. These methods work for most types of files, including text, photos, documents, and others.
Tip
This also works for removing spaces in a file name.
Note
Renaming a folder containing files may cause problems if that folder contains files that are required by a program. For example, if the program is looking for a folder named «data» and you rename it to «other» the program would no longer know where data files are located.
Method one
- Highlight the file or folder.
- Right-click the file with your mouse and select Rename from the menu that appears.
Tip
In Windows 11, select Show more options in the right-click menu to see the Rename option.
Method two
- Highlight the file or folder.
- Press F2 on the keyboard.
Method three
- Highlight the file or folder.
- Click File at the top of the window and select Rename from the list of available options.
Tip
File Explorer in Windows 11 does not have a file menu like previous versions of Windows. Instead, click the Rename icon in the menu bar at the top.
Method four
- Highlight the file or folder.
- Once highlighted, wait a few seconds and click the file name again. A box should appear surrounding the file or folder name, and you can rename the file.
Note
If you don’t wait long enough and click the file or folder too fast, it can open it rather than allowing you to rename it.
Renaming multiple files or folders at once
- Open Explorer.
- In Explorer, select all the files you want to rename.
- How to select or highlight multiple files and folders.
- Once the files are selected, press F2 to edit the file name and type the new name for the files. For example, typing «test» renames the files to test, test(1), test(2), test(3), etc. If you have file extensions displayed, make sure to also type the name of the file extension.
Microsoft Windows users can also rename any file using the Windows command line.
How to rename in MS-DOS and the Windows command line
MS-DOS and Windows command (CMD) line users can change the name of a file or directory using the ren or rename command. Below are examples of how this command can be used. Additional information about these commands is found by clicking the command links above.
- How to get to an MS-DOS prompt or Windows command line.
Renaming a file
The following example renames the file test.txt to hope.txt.
rename test.txt hope.txt
If the test.txt file is not located in your current directory, you must specify the file’s path as a prefix to the file name. For example, if the file is in the «computer» directory, type a command similar to the following example.
rename c:computertest.txt hope.txt
Renaming a file with a space
If a file or directory has a space, it must be surrounded with quotes. Otherwise, you get the «The syntax of the command is incorrect» error. To rename the file «computer hope.txt» to «example file.txt«, your command would resemble the following example.
rename "computer hope.txt" "example file.txt"
Renaming multiple files with one command
To rename multiple files at once, you must utilize some form of wild character. Below are examples of how this could be done.
The following example renames all the files in the current directory that end with .rtf to .txt files.
rename *.rtf *.txt
In this next example, the command renames a file with an unknown character in the file name to something that can be read. The «?» used in the following example is the wild character for an unknown character.
rename h?pe.txt hope.txt
Renaming a directory
Renaming a directory in MS-DOS is much like renaming a file. Use the ren or rename command to rename the directory. Because you cannot have a file and directory of the same name, you don’t need to worry about mistakenly renaming a file instead of a directory. The only exception is if you’re using wild characters.
Note
Renaming a directory containing files may cause problems if that directory contains files required by a program. For example, if the program is looking for a directory named «data» and you rename it to «other,» the program would no longer know where data files are located.
The following example renames the computer directory to hope.
rename computer hope
Rename the directory «computer hope» to «example directory». Whenever dealing with a file or directory with a space, it must be surrounded with quotes. Otherwise, you get the «The syntax of the command is incorrect» error.
rename "computer hope" "example directory"
Rename in a batch file
To rename files in a batch file, you can use any of the rename commands or examples shown in the MS-DOS and Windows command line section.
How to rename in macOS
Apple macOS users can rename their files and directories using one of the following methods. We’ve listed the following recommendations in what we believe to be the easiest methods of renaming a file.
First recommendation
In the macOS Finder, select the file by clicking the file once and then press return on the keyboard. After pressing return, type the new name of the file.
Second recommendation
Select the file or icon you want to rename. Click and then hover over the file name until it is highlighted. Once highlighted, this indicates the file can be renamed.
Third recommendation
Using the Terminal, you can also rename any file. See our Linux and Unix users section for steps on renaming a file using the mv command.
How to rename in the Linux and Unix command line
For detailed information about renaming files in Linux, see the Linux mv command.
How to rename in Google Chrome OS
With the Google Chrome OS on a Chromebook, you can rename your files and directories using one of the following methods. We’ve listed the following recommendations in what we believe to be the easiest methods of renaming a file.
First recommendation
Highlight the file by clicking the file once. Press Ctrl+Enter on the keyboard and then type the new name of the file.
Second recommendation
Right-click the file by pressing two fingers on the touchpad at the same time. In the right-click menu, click Rename and then type the new file name.
How to rename a document in Word or Excel
- Open the document you want to rename.
- Click File, then click Save As.
- In the Filename box, type the new name.
- Click Save. At this point, you can delete the old file or keep it as a backup.