Copy files in windows folder

Copy Files and Folders in Windows CMD with Copy and Xcopy

In this tutorial, we will learn how to copy files and folders in the Windows Command prompt.

We are going to look at two cmd commands: Copy and Xcopy.

Note that the copy command has some limitations compared to the xcopy. For example, to copy directories or hidden files, you have to use the xcopy command.

Copy Command

On Windows, we can use the copy command to copy one or more files from one location to another:

copy C:\data\sales.doc C:\backup

The preceding command will copy sales.doc from C:\data\ to C:\backup.

Use the /y switch to overwrite duplicate files without confirmation:

copy /y C:\data\sales.doc C:\backup

We can also save a file to a different name. For example, the following command saves file1.txt as file2.txt in the same directory:

copy file1.txt file2.txt

You can also use wildcards to copy multiple files:

copy /y C:\data\* C:\backup
copy /y C:\data\*.doc C:\backup

The first command copies all files in the C:\data\ directory to C:\backup. The second command copies all files with a .doc extension to the C:\backup.

windows copy command

We can also combine several files into one:

copy file1+file2 file3
copy error* C:\backup\report.txt

In the first line, file1 and file2 are combined to make one file named file3. In the second line, all files whose names start with «error» are copied to the C:\backup, as a single file called report.txt.

You can get a list of all available options with the copy /? command.

Xcopy Command

The xcopy command offers more features. For example, with xcopy, we can copy directories and subdirectories, as well as hidden files.

Command Options

/Y Prompt before overwriting an existing file.
/H Copy hidden files/system files.
/S Copy directories and subdirectories. Empty directories are not included by default (use /e for that).
/E Include empty directories.
/I Create the destination folder if it does not exist. Use this option when you want to copy the parent folder itself.
/T Copy directory tree without files. Empty directories are not included by default. Use /e option to include empty folders.
/P Prompt for confirmation before creating each file.
/Q Quiet mode.
/exclude Specify a text file that contains a list of files to exclude. See the examples.
/Z Resume mode. Use this option when copying files over a network.
/D:m-d-y Copies files changed on or after the specified date.

Examples of Using the Xcopy Command

Copy sales.doc from the current directory to C:\backup:

xcopy sales.doc C:\backup

Copy C:\data\accounts (all files including subdirectories) to C:\backup:

xcopy /s /e /h /i /y C:\data\accounts C:\backup\accounts

xcopy command

In the following example (without /I switch), the contents of the folder are copied but not the folder itself:

xcopy /s /e /h /y C:\data\accounts C:\backup\

Copy the directory structure of C:\OneDrive to the backup directory:

xcopy /s /e /t /y C:\OneDrive C:\backup\

You can use wildcard characters to match patterns. The following command copies all files with a .jpg extension:

xcopy /s /h /y C:\data\*.jpg C:\backup

Using for loop to copy multiple files:

for %i in (sales.doc, products.doc) do xcopy /y %i C:\backup

Excluding files with xcopy

With the /exclude, we can provide a text file that contains items we want to exclude.

xcopy /s /e /h /y /exclude:C:\Users\user1\files-to-exclude.txt C:\data\ C:\backup\

The files-to-exclude.txt may look like the following:

.doc
sales*

In this example, we exclude items with the .doc extension and files whose name starts with sales.

You can get a list of all available options with the xcopy /? command.

При работе в командной строке (cmd) часто возникает необходимость скопировать файл или целую папку. Также консольные команды для копирования могут использоваться в BAT-файлах для резервного копирования и других задачах.

В этой статье мы расскажем о том, как скопировать файл или папку в командной строке Windows. Статья будет актуальной для всех версий Windows, включая самые новые Windows 11 и Windows 10.

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

Для копирования файлов в командной строке Windows нужно использовать команду «copy». Данная команда позволяет скопировать один или несколько файлов из одной папку в другую. Обратите внимание, команда «copy» копирует только файлы. Для копирования вложенных папок нужно использовать команду «xcopy», которую мы рассмотрим ниже.

В самом простом случае команда для копирования файлов выглядит так:

copy [исходный файл] [новый файл или папка назначения]

Например, чтобы скопировать файл «file1.txt» из текущего каталога в папку «e:\tmp» нужно выполнить:

copy file1.txt e:\tmp

скопировать файл в папку

При необходимости для копируемого файла можно указать новое название в папке назначения. Например, чтобы скопировать «file1.txt» из текущего каталога в папку «e:\tmp» и при этом назвать его «newfile.txt» нужно выполнить:

copy file1.txt e:\tmp\newfile.txt

указать новое название файла в папке назначения

С указанием полных путей команда копирования будет выглядеть так:

copy d:\tmp\file1.txt e:\tmp\file.txt

копирование с указанием полных путей

Для копирования большого количества файлов в названиях можно использовать маски. Символ звездочка (*) обозначает любое количество любых символов, а знак вопроса (?) – один любой символ. Например, чтобы скопировать все документы с расширением TXT из текущего каталога в папку «e:\tmp\» нужно выполнить следующее:

copy *.txt e:\tmp\

копирование с использованием маски

Также с помощью команды «copy» можно скопировать все содержимое одной папки в другую. Например, в случае копирования всех файлов из папки «d:\tmp\» в папку «e:\tmp» команда будет выглядеть так:

copy d:\tmp\ e:\tmp

скопировать все содержимое одной папки в другую

В данном случае из папки «d:\tmp\» будут скопированы только файлы. Для копирования вложенных папок нужно использовать «xcopy».

Полный синтаксис команды «copy» выглядит так:

copy [/d] [/v] [/n] [/y | /-y] [/z] [/a | /b] <source> [/a | /b] [+<source> [/a | /b] [+ ...]] [<destination> [/a | /b]]

Полный список параметров для команды «copy»:

Параметр Описание
/d Сохранение копируемых зашифрованные файлов в расшифрованном виде в месте назначения.
/v Проверка правильности записи скопированных файлов.
/n Использование короткого имени файла (если доступно) при копировании файла с именем длиннее восьми символов или с расширением длиннее трех символов.
/y Подавление запроса на подтверждение перезаписи.
/-y Вывод запроса на подтверждение перезаписи.
/z Копирует сетевые файлы в перезапускаемом режиме.
/a Копирование текстового файла ASCII.
/b Копирование двоичного файла.
<source> Указывает расположение, из которого необходимо скопировать один или несколько файлов. Обязательный параметр.
<destination> Указывает расположение, в которое необходимо скопировать файл или несколько файлов. Обязательный параметр.
/? Отображение справки в командной строке.

Большинство параметров указываются в начале, сразу после команды «copy». Например, для того чтобы подавить вывод запросов на перезапись существующих файлов можно добавить параметр «/y».

copy /y file1.txt file2.txt

Как скопировать папку через командную строку Windows

Для копирования папок с вложенными папками и файлами в командной строке Windows нужно использовать команду «xcopy». Данная команда позволяет скопировать папку из одного расположение в другое с сохранением структуры каталогов. Фактически «xcopy» — это более продвинутая версия команды «copy».

В упрощенном виде синтаксис команды «xcopy» будет выглядеть так:

xcopy [исходная папка или файл] [папка назначения или файл] [параметры]

Для копирования папок с вложенными папками и файлами нужно использовать параметр «/s» или «/e». Без этих параметров команда будет работать только с одним каталогом.

Параметр Описание
/s Копирование каталогов с подкаталогами (исключая пустые)
/e Копирование каталогов с подкаталогами (включая пустые).

Например, для того чтобы скопировать все файлы и вложенные папки (включая пустые) из папки «d:\tmp» в папку «e:\tmp» нужно выполнить:

xcopy d:\tmp e:\tmp /e

скопировать все файлы и вложенные папки

Полный синтаксис команды «xcopy» выглядит так:

xcopy <Source> [<Destination>] [/w] [/p] [/c] [/v] [/q] [/f] [/l] [/g] [/d [:MM-DD-YYYY]] [/u] [/i] [/s [/e]] [/t] [/k] [/r] [/h] [{/a | /m}] [/n] [/o] [/x] [/exclude:FileName1[+[FileName2]][+[FileName3]]] [{/y | /-y}] [/z] [/b] [/j]

Полный список параметров для команды «xcopy» можно посмотреть на сайте Майкрософт. Здесь же приведены только некоторые самые базовые:

Параметр Описание
/s Копирование каталогов с подкаталогами (исключая пустые)
/e Копирование каталогов с подкаталогами (включая пустые).
/w Вывод запроса на подтверждения начала копирования.
/p Запрос подтверждение при создании каждого нового файла.
/c Пропуск ошибок.
/v Проверка всех скопированных файлов на соответствие его исходнику.
/q Скрывает вывод информации от команды xcopy.
/f Вывод имен в процессе копирования.
/l Вывод списка копируемых файлов.
/g Сохранение новых файлов в незашифрованном виде.
/d[:мм-дд-гггг] Копирование файлов, которые были измененные не ранее указанной даты. Если не указать дату (мм-дд-гггг), то команда xcopy будет копировать все файлы, которые новее существующих.
/u Обновление только существующих файлов в папке назначения.
/y Подавление запроса на подтверждение перезаписи.
/-y Вывод запроса на подтверждение перезаписи.
/z Копирует сетевые файлы в перезапускаемом режиме.
/h Копирование скрытых и системных файлов.
/r Перезапись файлов с атрибутом «только для чтения».
/t Создание структуры каталогов без копирования файлов. Пустые каталоги не включаются в структуру. Для включения пустых каталогов нужно добавить параметр /E.
<source> Указывает расположение, из которого необходимо скопировать один или несколько файлов. Обязательный параметр.
<destination> Указывает расположение, в которое необходимо скопировать файл или несколько файлов. Обязательный параметр.
/? Отображение справки в командной строке.

Параметры указываются в конце команды. Например, для того чтобы скопировать все файлы (включая скрытые, системные и только для чтения) и вложенные папки (включая пустые) из папки «d:\tmp» в папку «e:\tmp» нужно выполнить:

xcopy d:\tmp e:\tmp /e /h /r

Посмотрите также:

  • Выключение компьютера через командную строку
  • Как перезагрузить компьютер через командную строку
  • Как вызвать командную строку в Windows 7
  • Как поменять дату в Windows 7
  • Как выключить компьютер через определенное время

Автор
Александр Степушин

Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.

Остались вопросы?

Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.

Using copy command, we can copy files from one directory to another directory. This command is similar to the Linux cp command, but it does not match with the full functionality of cp. Windows copy command can be used to copy files only, we can’t copy directories.

The syntax and usecases of copy command are explained below with examples.

Copy the contents of a file to another file

copy sourceFile destinationFile

Example: To copy a file from c:\data\file1.doc to D:\backup\file2.doc

copy c:\data\file1.doc D:\backup\file2.doc

If the destination file already exists you will be prompted for confirmation. To suppress this confirmation you can use /Y switch with copy command. This would be useful if you are executing copy command from a batch file.

c\> copy /Y c:\dir1\subdir1\file1.txt  c:\dir2\subdir2\file2.txt

If the destination file exists, the above command will overwrite the same without asking the user for confirmation.

Copy file to another directory

When we specify a directory path as the destination, the files will be copied with the same name. We can assign a different name by specifying the new name in the destination path. Example is shown below.

To copy the file 1.doc loated at c:\data\documents to the directory c:\data\newdocs

c\> copy c:\data\documents\1.doc  c:\data\newdocs\

Copy files with white space in name

If the file name has white space within it, we can wrap up the name in double quotes.
Example: To copy file, my resume.doc to another folder

 copy "my resume.doc"  D:\data\

Copy multiple files

We can’t specify multiple file names in copy command. However, we can use wildcards to identify a group of files and then copy all of them in a single command.
For example, to copy all excel files from current folder to another folder F:\backup

copy *.xls F:\backup\

To copy all files in current folder to another folder

copy *   D:\dir1\dir2

Use of environment variables

We can use environment variables in the copy command to specify the path of the folders. Like USERPROFILE, SystemRoot, ProgramFiles, TEMP, WINDIR, APPDATA, HOMEPATH.

For example, to copy a file to a user’s documents folder

Copy D:\file.pdf %HOMEPATH%\Documents\

The above command copies the file to the My Documents folder of the current logged in user.

You may also want to read

  • Xcopy command syntax and examples
  • Robocopy command

Updated: 11/18/2022 by

Copying two files on the Windows 10 desktop.

To copy computer documents, pictures, or other files from one place to another, follow these instructions.

Note

A file name must be unique. If it’s not, a number is appended to the end of a file name. It may also have «- Copy» appended to the end of the file name, instead of a number. Appending a number to the end of the copied file’s name assures the copied file is unique. For example, if the original file name is abc123.pdf and a copy is created in the same directory or folder, the copied file name could be abc123(1).pdf or abc123 — Copy.pdf.

Select your operating system in the list below to view the instructions that apply to you.

How to copy a file in Microsoft Windows

Copying files in Windows

Below are the steps on how to copy a file or multiple files in Microsoft Windows from one location to another.

  1. Go to the files or folders you want to copy. If you need help locating the files, use the Windows find feature.
  2. Highlight the file or files you want to copy by clicking them once with the mouse. If you need to highlight more than one file, hold down the Ctrl or Shift keys on your keyboard, or drag a box around the files you want to copy.
  3. Once highlighted, right-click one of the highlighted files and select Copy. Users may also press the Ctrl+C keyboard shortcut, or in Windows Explorer, click Edit at the top of the window and select Copy.
  4. Open the destination folder, right-click an empty space in the folder, and select Paste. Or, in the menu bar at the top, click File, choose Edit, then select Paste.
  • How to select or highlight multiple files and folders.

Tip

To copy only a certain type of file, click the Type column in Windows Explorer. This action sorts files by type, rather than by name. Once grouped by type, you can select only the files with the type you want to copy, and then copy those files.

Tip

You can also use the Windows command line to copy files. In some situations, such as copying multiple files of a certain extension or with a certain name, it can be easier.

How to copy a file in MS-DOS and the Windows command line

copy command

Below are steps on how to copy a single file from one directory to another directory in MS-DOS or the Windows command line.

Copying a single file

  1. Using the cd command, move to the directory containing the file you want to copy.
  2. Type a command similar to the following.
copy myfile.txt c:\my\location

In the example above, substitute «myfile.txt» with the name of the file you want to copy, and «c:\my\location» with the destination directory. To see files available in the current directory, use the dir command.

Copying multiple files to another location

Below are the steps on how to copy multiple files from one directory to another directory.

  1. Using the cd command, move to the directory containing the files you want to copy.
  2. Once in the directory containing the files you want to copy, type a command similar to one of the following commands.
copy *.* c:\mydir

In the example above, the command would copy every file in the current directory to the «mydir» directory.

copy *.txt c:\mydir

In the example above, the command would copy every txt, or text file, in the current directory to the «mydir» directory.

Tip

For additional examples of wildcard characters, see our wildcard definition.

xcopy hope example /e

If you need to copy files, directories, and subdirectories, use the xcopy command. In the example above, the xcopy command copies all directories (even empty directories) and files from the «hope» directory to the example directory.

Copying long file name files or files with spaces

Often, you can encounter a file with spaces in the file name. To copy these files, surround the full file name and file extension in quotes.

copy "computer hope.txt" "there is hope.txt"

In the example above, the «computer hope.txt» file is surrounded in quotes to let the command line know the complete file name, thus eliminating the spaces.

How to copy files to another drive

You can also copy files from the current location to any other drive. For example, if you have a USB (universal serial bus) flash drive that is drive letter F:, you can use the following command to copy all JPEG (Joint Photographic Experts Group) image files to the flash drive.

copy *.jpg f:
  • How to change drives in MS-DOS and Windows command line.

How to make a copy of a file into the same directory

copy example.txt backup.txt

In the example above, the file «example.txt» is copied to the same directory as «backup.txt,» effectively making a backup copy of the file.

Related pages and help

  • See the cd command, dir command, copy command, and xcopy command pages for further information about each MS-DOS command.
  • How to use the Windows command line (DOS).

Batch file

To perform any copy command in a batch file, include any of the Windows command line copy commands above in a batch file.

  • How to make a batch file.

How to copy files in Linux and Unix

cp command

Below are steps on how to copy a single file from one directory to another directory in Linux and Unix.

Copying a single file from one location to another

  1. Using the cd command, move to the directory containing the file you want to copy.
  2. Type a command similar to the following.
cp myfile.txt /usr/bin

In the example above, substitute «myfile.txt» with the name of the file you want to copy, and «/usr/bin» with the destination directory. To see files available in the current directory, use the ls command.

Copying multiple files to another location

Below are the steps on how to copy multiple files from one directory to another directory.

  1. Using the cd command, move to the directory containing the files you want to copy.
  2. Once in the directory containing the files you want to copy, type a command similar to one of the following commands.
cp *.* /usr/bin

In the example above, the command would copy every file in the current directory to the «/usr/bin» directory.

cp *.txt /usr/bin

In the example above, the command would copy every txt, or text file, in the current directory to the «/usr/bin» directory.

For additional examples of wildcard characters, see our wildcard definition.

Copying files with spaces in the file names

Often, you can encounter a file with spaces in the file name. To copy these files, surround the full file name and file extension in quotes.

cp "computer hope.txt" "there is hope.txt"

In the example above, the «computer hope.txt» file is surrounded in quotes to let the command line know the complete file name. In our example, the destination file name contains whitespace (spaces), so the name is enclosed in quotes.

How to make a copy of a file into the same directory

cp example.txt backup.txt

In the example above, the file «example.txt» is copied to the same directory as «backup.txt,» effectively making a backup copy of the file.

Related pages and help

  • See the cd command, cp command, and ls command pages for additional information about these commands.
  • For general help using the Linux command line, see our Linux and Unix shell tutorial.

How to copy files in Apple macOS

Drag-and-drop

Highlight the files you want to copy. Then, click the highlighted files with the left mouse button and, while continuing to hold down the mouse button, drag-and-drop the files to where you want to copy them. When you release the mouse button, the files are copied.

Keyboard shortcut

You can also copy files using keyboard shortcuts by following these steps.

  1. Highlight the files you want to copy.
  2. Press the keyboard shortcut Command+C.
  3. Move to the location you want to move the files and press Command+V to copy the files.

Terminal

To copy files in a Terminal session, use the cp command.

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

Есть несколько способов перемещения файлов и папок в компьютере. Но мы рассмотрим универсальный — тот, которым можно перенести информацию с CD или DVD диска, записать данные на флешку и с флешки. Также при помощи него можно переписать фото или видео с фотоаппарата (видеокамеры), с мобильного телефона и с других подключаемых к компьютеру устройств.

Перемещение объектов из одного компьютерного места в другое называется копирование. Это такой процесс, при котором мы создаем точную копию данных и отправляем ее в другое место.

Пошаговая инструкция

  1. Щелкните правой кнопкой мышки по объекту, который хотите перенести. В открывшемся списке нажмите на пункт «Копировать».
  2. После этого нужно открыть на компьютере тот отдел, куда Вы хотите отправить данные. Это может быть Локальный диск D, Документы или любая другая папка, Рабочий стол и даже флешка.
  3. Затем щелкните правой кнопкой мышки по пустой части (не по какому-то значку, а рядом) и из списка выберите пункт «Вставить».

Вот и всё! Теперь этот объект есть в двух местах: и в том , откуда мы его взяли, и в новом (там, куда перенесли).

Получается следующее:

  • Вы открыли место, из которого хотите взять файл (например, флешку).
  • Кликнули по нему ПКМ (правой кнопкой мышки), выбрали из списка «Копировать».
  • Затем перешли в раздел, куда хотите перенести этот объект (например, Документы).
  • Нажали по пустой области ПКМ и выбрали «Вставить»

Копирование нескольких файлов/папок

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

Нажмите левую кнопку мыши и, не отпуская ее, обведите прямоугольником необходимые объекты. Когда они закрасятся цветом, это будет означать, что все они выделены. Отпустите мышку.

А теперь скопируем их. Щелкните ПКМ по любому выделенному значку. Откроется список, из которого нужно выбрать пункт «Копировать».

Затем откройте на компьютере то место, в которое хотите поместить эти данные. Это может быть Локальный диск D, Документы, флешка или какая-то папка.

И, наконец, нажмите ПКМ по пустому полю, и из появившегося списка выберите пункт «Вставить».

Всё! Файлы и папки перенеслись в новое место. То есть они теперь в двух местах: и там, где были изначально, и в новом – там, куда Вы их скопировали.

Не пугайтесь, все не так сложно, как кажется на первый взгляд. Нужно только чуть-чуть потренироваться. Удачи!

  • Компьютерная грамотность
  • Microsoft Word
  • Microsoft Excel
  • Уроки Интернета
  • Электронная почта
  • Социальные сети
  • Архив уроков

  • Copy trance heic for windows скачать бесплатно
  • Contacts backup скачать для windows phone
  • Connectify скачать на русском языке для windows 7 скачать бесплатно на русском
  • Connectify hotspot скачать бесплатно на русском языке для windows 7
  • Copy files from windows to ubuntu