Команды linux для работы с файлами

Синтаксис

После индекса жесткого диска обязательно ставить двоеточие и две косых линии — //. К слову, вы можете использовать // или \ без каких-либо различий для команды. С помощью стрелочек вверх и вниз пользователь может перемещаться между ранее набранным текстом. Если вы используете одну и ту же команду несколько раз, то имеет смысл пользоваться такой функцией.

Перейти в папку из командной строки Windows оказалось довольно просто. Если у вас возникнут проблемы с работоспособность проводника, то эта ситуация не застанет вас врасплох.

В создании этой статьи участвовала наша опытная команда редакторов и исследователей, которые проверили ее на точность и полноту.

Команда контент-менеджеров wikiHow тщательно следит за работой редакторов, чтобы гарантировать соответствие каждой статьи нашим высоким стандартам качества.

В этой статье рассказывается, как перейти в другую папку (каталог) в командной строке Windows. Чтобы работать с командной строкой, необходимо использовать учетную запись администратора.

Источник

How to view the contents of a directory in Command Prompt (CMD)

You can view the contents of a folder by using a command called DIR. To test it, we have created a folder named Digital_Citizen on the D: drive, with several files and subfolders. You can see them in the screenshot below.

A folder found in the root of the D drive

The last time, our working folder was «C:\Windows.» To navigate to the folder mentioned above, we have to use the command «cd /d D:\Digital_Citizen.» To view the contents of the folder, type DIR, and press Enter. The list of the files and folders contained by it is displayed, together with some details about each of them (the size and the date and time when they were last modified).

Using the DIR command to see the contents of a directory

Cd syntax

Windows XP and later syntax

CHDIR  
CHDIR 
CD  
CD 

.. Specifies that you want to change to the parent directory.

Type CD drive: to display the current directory in the specified drive. Type CD without parameters to display the current drive and directory.

Use the /D switch to change current drive in addition to changing current directory for a drive.

If Command Extensions are enabled CHDIR changes as follows:

The current directory string is converted to use the same case as the on-disk names. So CD C:\TEMP would set the current directory to C:\Temp if that is the case on disk.

CHDIR command does not treat spaces as delimiters, to CD into a subdirectory name containing a space without surrounding the name with quotes. For example:

chdir \winnt\profiles\username\programs\start menu

is the same as:

cd "\winnt\profiles\username\programs\start menu"

which is what you would have to type if extensions were disabled.

How to create a new directory with Command Prompt (CMD)

You can make a new folder using the MKDIR (Make Directory) or the MD command. The syntax of these commands is «MKDIR Folder» or «MD Folder.»

Let’s say we need to create a new folder called Digital_Citizen_Life that is going to be placed in the «D:\Digital_Citizen» folder. To do that, we need to type «mkdir Digital_Citizen_Life» and then press Enter, as shown below.

The MKDIR command, in Command Prompt

To test if it worked, use the DIR command again. The newly created folder appears in the list.

Using DIR to see the contents of the directory, in Command Prompt

NOTE: Do not forget that all these commands depend on the current location in the Command Prompt. For instance, if you are on the «C:» drive and type «MKDIR test,» the new folder is created in the root of the «C:» drive.

Another way to create a folder that does not involve being in the desired folder is to type the complete path of the new folder. For example, if you are working on the «D:» drive and you want to create a new folder in «C:,» called other_stuff, type «mkdir c:\other_stuff» and then press Enter.

Using MKDIR to create a new directory, with a full path

When you need to create a folder with subfolders at the same time, you can use the «MKDIR FolderSubfolder» command. For instance, if we type «mkdir Digital_Citizen_Tests\Beta\Test1» three folders are created: Digital_Citizen_Tests, Beta and Test1, in a tree-like structure.

Creating a folder with subfolders, using MKDIR in Command Prompt

Cd examples

cd\

Goes to the highest level (the root) of the drive.

cd..

Moves back one directory. For example, if you are in the C:\Windows\COMMAND> directory and type the above command it would take you to C:\Windows> directory.

Tip

With Windows 95 and later, you can go back more than one directory when using more than two periods. For example, typing cd… (three periods) would take you back two directories (if possible) instead of only one directory.

cd windows

If this directory is available in the current directory, it takes you into the Windows directory. The directory name «Windows» can be substituted with any other directory name and in MS-DOS and the Windows command line capitalization is not important.

Tip

If at any time you need to see what directories are available in the directory you’re currently in, use the dir command.

cd\windows

If this directory is available, it would first move back to the root of the drive and then go into the Windows directory. The C:\Windows directory is the default install directory, so on almost all computers this directory should be valid.

cd\windows\system32

If this directory is available, it changes into the system32 directory, a subdirectory of the Windows directory.

cd /d e:\pics

For example, if you were on the C: drive, using the /d option switches to the E: drive and then moves into the pics directory.

cd

Typing cd alone prints the working directory. For example, if you’re in c:\windows> and you type the cd it prints «c:\windows.» For those users who are familiar with Unix or Linux, this could be thought of as doing the pwd (print working directory) command.

How to rename files and folders with Command Prompt (CMD)

To rename files and folders, you need to use the REN (Rename) command. To rename folders, type «ren Folder NewFolderName.» For example, if we wanted to rename the Digital_Citizen_Tests folder to Digital_Citizen_Final_Tests, we should run «ren Digital_Citizen_Tests Digital_Citizen_Final_Tests» and press Enter.

Renaming folders with the REN command, in Command Prompt

To rename a file, use the same command, like this: «ren filename.extension newname.extension». For instance, to rename the Digital_Citizen_Picture1.bmp file to Image0.bmp, we have to run the command «ren Digital_Citizen_Image1.bmp Image0.bmp» command.

Renaming files with the REN command, in Command Prompt

Дополнительные команды

Команда FORMAT в CMD позволяет стереть информацию с винчестера или подготовить его для копирования данных, если вы установили новый диск. Синтаксис для использования команды: FORMAT диск:. Если вы хотите переформатировать конкретный диск под конкретную файловую систему, вы можете сделать это с помощью команды: FORMAT диск: / FS: файловая-система, где файловая-система может быть: FAT, FAT32 или NTFS. После применения команды все данные с диска будут бесследно стерты.

FC — используется для сравнения двух файлов друг с другом. Предположим, у вас есть два файла gadgets360_1.txt и gadgets360_2.txt. Чтобы сравнить их, нужно ввести следующую команду: FC gadgets360_1.txt gadgets360_2.txt.

IPCONFIG выводит подробную информацию о сетевых настройках: IP-адрес, а также сообщает тип сетевого соединения вашего компьютера (с помощью Wi-Fi или Ethernet). Введите IPCONFIG / ALL, чтобы получить обзор всех сетевых настроек, включая то, какие DNS-серверы вы используете. Введите IPCONFIG / RENEW, чтобы получить новый IP-адрес с сервера DHCP. Это может помочь, если у вас возникли проблемы с подключением к интернету.

CMD ping команда — если вы не уверены, доступен ли сайт, который вы хотите посетить, введите PING, за которым следует IP-адрес или доменное имя. Например, PING google.com. Если на экране появится надпись Destination Net Unreachable, возможно, у вас отсутствует подключение к интернету. Если появятся сообщения Host is down или Request timeout, сайт может быть недоступен. Если все в порядке, вы должны увидеть что-то похожее на это: 64 bytes from 173.194.36.73: icmp_seq=0 ttl=56 time=118.355 ms.

Команда SHUTDOWN может пригодиться вам, если кнопка «Завершение работы» в меню «Пуск» не работает из-за действия вредоносных программ. Для завершения работы компьютера (для Windows) введите Shutdown / S. Чтобы перезапустить компьютер — Shutdown / R.

CHKDSK — CMD команда используется для того, чтобы проверить, может ли ваша операционная система правильно прочитать жесткий диск или любой другой носитель. Синтаксис команды: CHKDSK C: — замените C буквой диска, который нужно проверить. Введите CHKDKS /? чтобы посмотреть другие варианты.

How to Change Directory in CMD with CD Command

Step 1. Open Windows Command Prompt Utility

Before you use Command Prompt to change directory, you should enter into Command Prompt at first.

You can press Windows + R, type cmd, and press Ctrl + Shift + Enter to open elevated Command Prompt in Windows 10.

Step 2. How to Use CD Command in CMD to Change Directory

Then you can type CD command lines in CMD to change different directory or folder paths.

If you want to go to a specific directory, you can type cd + full directory path, e.g. cd C:\Program Files.

To open a particular folder, you can type cd + full folder path, e.g., cd C:\Program Files\office.

To go up a directory level you are currently working, you can type cd ..

To check the whole subdirectories and folders in the current directory, you can type dir command.

To go to the root level directory from any directory, you can type cd \.

To change the current drive, you can firstly type cd \ to go to the root directory, and then enter the drive letter followed by a colon to enter the target drive, e.g. I:.

To change the drive and directory at the same time, you can use CD and the /D switch simultaneously, e.g., cd /D I:\MiniTool Partition Wizard 11.

Show Folder Size in Windows 10 | Fix Folder Size Not Showing

This post teaches you how to show/view folder size in Windows 10 File Explorer if Windows folder size is not showing. 4 ways are included.

Read More

Bottom Line

Now you should know how to change directory in Command Prompt (CMD) by using CD command in Windows 10. You can easily access different directories or folders with CD command Windows in Command Prompt.

If you can’t find a file or folder in your Windows 10 computer, you may lost it or mistakenly deleted it, you can easily recover the file or folder with MiniTool Power Data Recovery.

MiniTool Power Data Recovery is a professional free data recovery program compatible with Windows 10/8/7. You can use this software to easily recover data from various data loss situations.

Namely, you can recover any deleted/lost files from Windows 10/8/7 computer, external hard drive, USB/thumb/pen drive, SD card, and more.

For the data loss due to mistaken file deletion, system crash and other computer system issues, hard drive failure, malware/virus infection, etc. you can use MiniTool Power Data Recovery to easily retrieve the lost files and data.

How to Corrupt a File with Top 3 Free File Corrupters

How to easily corrupt a file like Word, Text, Excel, PDF, MP3 file, etc. so it won’t open? Here are 3 free file corrupters to let you corrupt a file online.

Read More

How to change the directory (folder) in Command Prompt (CMD)

The first command from the list is CD (Change Directory). This command enables you to change the current directory or, in other words, to navigate to another folder from your PC. For instance, the command CD takes you to the top of the directory tree. To see how it works, after you open the Command Prompt, type cd and press Enter on your keyboard. You should see how the CD command takes you to the top of the directory tree. In this case, to the «C:» drive.

Running the CD command to change the directory to root

Note that the Command Prompt is not case sensitive, meaning that you can type commands using capital letters, lowercase or any combination of them. The commands CD, cd or Cd, all work the same way.

Going back to the «CD» command, now you are working on the root of the «C:» drive. If you need to go to a specific folder from this drive run the command «CD Folder.» The subfolders must be separated by a backslash character: «.» For instance, when you need to access the System32 folder located in «C:\Windows,» type «cd windows\system32» as shown below, and then press Enter on your keyboard.

Running the CD command to change the directory to a specific folder

When you need to go one folder up, use the «cd..» command. Let’s assume that you want to go back to the Windows folder. Type «cd..» and press Enter on your keyboard.

Running the CD.. command to go up one level in the directory tree

The effect is that your current directory changes to «C:\Windows.»

Основные команды командной строки

DIR — сокращение от Directory, эта CMD команда для новичка выводит список всех файлов и папок в определенном каталоге. А также их размер, расширение и свободное пространство, оставшееся на диске. Команда dir в командной строке может быть изменена с помощью дополнительных параметров, таких как DIR /р (выводит список по страницам), DIR /q (выводит информацию о владельце сайта), DIR /w (выводит список в расширенном формате с максимальным количеством файлов в одной строке), DIR / d (выводит список в расширенном формате с разбивкой на столбцы), DIR /n (выводит длинный список одной строкой), DIR /l (выводит несортированный список имен каталогов и файлов в нижнем регистре), DIR /b (выводит список файлов без дополнительной информации). DIR /s выводит список файлов и директорий данного каталога, а также всех подкаталогов. Введя DIR/?, вы увидите список всех доступных параметров.

Команда CD командной строки или CHDIR (Change Directory) предназначена для того, чтобы сменить каталог. Команда выполняет несколько операций. CD перемещает вас на самый верх дерева каталогов. CD .. перемещает вас в родительский каталог по отношению к текущему. CD имя-каталога перемещает вас в этот каталог. Введите CD, чтобы вывести на экран имя текущего каталога.

MD или MKDIR (Make Directory) позволяет создать каталог (папку). Чтобы создать каталог, используйте следующий синтаксис: MD имя-каталога.

CLS очищает экран. Эта команда CMD в Windows применяется, если эмулятор командной строки заполнен перечнем команд и их операций.

EDIT имя-файла позволяет изменять содержимое файла.

Команда DEL позволяет удалить один или несколько файлов. В качестве альтернативы можно использовать команду ERASE. Для удаления файла используйте синтаксис DEL имя-файла.

Если вы хотите удалить все файлы с определенным расширением, то введите DEL *.doc, и из текущего каталога будут удалены все файлы с расширением doc. DEL *.* удаляет все файлы из текущего каталога, поэтому будьте осторожны с этой командой.

RD или RMDIR — вы можете использовать эту команду, чтобы удалить папку, но папка должна быть пустой. Синтаксис довольно прост. Введите RD имя-папки. Если вы хотите удалить папку, которая не является пустой, вы можете использовать RD / S имя-папки. Будьте осторожны с этой командой, так как она удаляет папку и все ее содержимое без возможности восстановления.

RENAME, или REN переименовывает файл или каталог. Синтаксис этой команды CMD управления компьютером следующий: RENAME текущее-имя новое-имя. Например, если вы хотите переименовать файл с именем iPhone.txt в iPad.txt, введите RENAME iPhone.txt iPad.txt.

MOVE позволяет переместить один или несколько файлов из одного каталога в другой. Например, если вы хотите переместить файл 1.txt размещенный в текущей директории в папку с именем Numericals внутри текущего каталога, введите MOVE 1.txt Numericals. Если вы пытались переименовать директорию (папку) с помощью команды RENAME приведенным выше способом, то знаете, что это не работает. В этом нам поможет команда MOVE, так как она также может быть использована для переименования каталогов. Введите MOVE текущее-имя новое-имя, где текущее имя — это имя директории в текущей папке.

Команда COPY позволяет скопировать один или несколько файлов из одного места в другое. Команда позволяет объединять файлы одного и того же типа. Давайте посмотрим на различные примеры применения команды COPY:

  • COPY имя-файла имя-папки скопирует файл имя-файла в уже существующую папку;
  • COPY имя-файла новое-имя-файла создает копию файла с новым именем;
  • COPY *.doc Word копирует все файлы с расширением .doc в папку с именем Word.

CMD основная команда XCOPY предназначена для файлов и каталогов, включая подкаталоги. Простейший вариант ее использования — скопировать все файлы с одного диска на другой. Синтаксис: XCOPY Исходный-диск: Диск-назначения: /e, где параметр /е позволяет копировать все подкаталоги, даже если они пусты. Используйте /s, чтобы запретить копирование пустых директорий. Вы можете использовать имена папок исходного диска или диска назначения, чтобы просто скопировать все содержимое одной папки в другую.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
/d /d Изменяет текущий диск, а также текущий каталог для диска. Changes the current drive as well as the current directory for a drive.
Указывает диск для вывода или изменения (если он отличается от текущего диска). Specifies the drive to display or change (if different from the current drive).

Указывает путь к каталогу, который требуется отобразить или изменить. Specifies the path to the directory that you want to display or change. Указывает, что вы хотите перейти к родительской папке. Specifies that you want to change to the parent folder.

/? /? Отображение справки в командной строке. Displays help at the command prompt.

How to change the drive in Command Prompt (CMD)

To access another drive, type the drive’s letter, followed by «:». For instance, if you wanted to change the drive from «C:» to «D:», you should type «d:» and then press Enter on your keyboard.

Changing the drive in Command Prompt

To change the drive and the directory at the same time, use the cd command, followed by the «/d» switch. The «/d» parameter is used to change the current drive to a specific folder from another disk volume.

For instance, if you are now on the «D:» drive and you want to go back to the Windows folder from the»C:» drive, you should type «cd /d C:\Windows» and press Enter on your keyboard, like in the following screenshot.

Changing the drive and directory in Command Prompt

NOTE: By typing only the drive letter you automatically move to your most recent location on that drive. For instance, if you are on «D:» drive and type «cd c:\windows» nothing seems to happen. However, if you type «c:» then the working folder changes to «c:\windows,» assuming that it was the last folder you worked with on your «C:» drive.

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

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

Adblock
detector