- Команда COPY
- Примеры использования COPY:
- Windows copy command syntax and examples
- Copy the contents of a file to another file
- Copy file to another directory
- Copy files with white space in name
- Copy multiple files
- Use of environment variables
- Команда COPY: копирование файлов в командной строке Windows
- Windows copying files cmd
- Combining files
- Binary copies
- Copy from the console (accept user input)
- Prompt to overwrite destination file
- Errorlevels
- Windows copying files cmd
- Syntax
- Parameters
- Remarks
- Examples
Команда COPY
Команда COPY используется для копирование одного или нескольких файлов в командной строке Windows.
Формат командной строки:
COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/A | /B] источник [/A | /B] [+ источник [/A | /B] [+ . ]] [результат [/A | /B]]
источник — Имена одного или нескольких копируемых файлов.
/A — Файл является текстовым файлом ASCII.
/B — Файл является двоичным файлом.
/D — Указывает на возможность создания зашифрованного файла
результат — Каталог и/или имя для конечных файлов.
/V — Проверка правильности копирования файлов.
/N — Использование, если возможно, коротких имен при копировании файлов, чьи имена не удовлетворяют стандарту 8.3.
/Y — Подавление запроса подтверждения на перезапись существующего конечного файла.
/-Y — Обязательный запрос подтверждения на перезапись существующего конечного файла.
/Z — Копирование сетевых файлов с возобновлением. Ключ /Y можно установить через переменную среды COPYCMD.
Ключ /-Y командной строки переопределяет такую установку.
По умолчанию требуется подтверждение перезаписи существующих файлов, если только команда COPY не выполняется в пакетном файле.
Команда copy позволяет объединить несколько файлов в один. Чтобы объединить файлы, укажите один конечный и несколько исходных файлов, используя подстановочные знаки или формат «файл1+файл2+файл3+. «.
По умолчанию, используется копирование файлов как двоичных «один в один», поэтому параметр /B можно не задавать. Параметр /A необходим, если в результатах копирования должны обрабатываться специальные символы, применяемые в текстовых файлах.
Ключ /N используется для совместимости с программами MS-DOS, не поддерживающих длинные имена файлов.
Примеры использования COPY:
copy /? — выдать справку об использовании команды.
copy file1.txt file2.txt — копировать файл file1.txt в файл file2.txt в текущем каталоге. Если файл file2.txt существует, то пользователю будет выдан запрос на подтверждение перезаписи существующего файла.
copy /Y file1.txt file2.txt — то же самое, что и в предыдущем примере, но запрос на подтверждение перезаписи существующего файла не выводится.
copy *.txt D:\oldfiles\*.txt — копирование всех файлов с расширением txt из текущего каталога в каталог D:\oldfiles
copy file1.txt + file2.txt +file3.txt file123.txt — копировать содержимое файлов file1.txt , file2.txt и file3.txt в файл file123.txt
copy C:\ndldr «D:\My Backup\system\ntldr» — при использовании имен файлов или каталогов, содержащих пробелы, используются двойные кавычки.
COPY /V file.bin A:\saved.bin — выполнить копирование файла на дискету A: с проверкой результата.
    Команда COPY может применяться для копирования файлов с использованием стандартных устройств ввода-вывода:
Windows copy command syntax and examples
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
Example: To copy a file from c:\data\file1.doc to 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.
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
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 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
To copy all files in current folder to another folder
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
The above command copies the file to the My Documents folder of the current logged in user.
You may also want to read
Windows «copy» is funny. Type «copy 1 2» and the file «1» will be copied into a new file «2». Now separate them by a plus sign instead of a space (copy 1+2) and you’ll concatenate 1 and 2 and replace the old file «1» with the result of the concatenation!
Yes, we can concatenate two or more files using copy command. You need to separate the list of files using +. You can redirect the resultant data to a new file also.
The above command will not alter the file 1. It creates a new file 3 with the concatenated data of 1 & 2. If no file name is provided it stores the result in the first file.
My Win7 cannot find a copy command, and when i run xcopy, a window flashes and exits.
I have the same problem. If you solved it, could you please explain how?
If you can not find your copy.exe file, you can download it to your windows directory or C:\ Directory depending the setting on your OS you should also be able to copy and run it from system32 or system folder.
how can i combine 2 .exe files and be able to use both after concatenation
I want to copy 2 different files(.exe,.config) from source to destination server of windows.
can you please help me on this command.
Hello i have a problem with my cmd windows 7.when i try to copy a command. Like help > file.pdf. i mean in extension pdf because i have this problem only with .pdf extension but not with .txt.So whe i execute the command. No problem. Then when i go to open the file.pdf ftom user destination the file.pdf doesn’t open say that is corrupted.please do help me .thanks
i have a file contain many lines as sources and another file has the same numbre of lines as destinations. i want to copy first line as source( c:/test/*.txt) to first line in destination ( d:/test2/), secend line ( c:/test/*.pdf) to second line in destination ( E:/test3/)……
Can I use the DOS/Windows “COPY” command in a BAT file to copy a file or a short string of text to computer memory and then paste (Ctrl +V) that string or file into a document?
Команда COPY: копирование файлов в командной строке Windows
Для копирования одного и нескольких файлов в командной строке Windows существует команда COPY. Она довольно проста в использовании и при этом весьма функциональна.
Синтаксис команды copy :
COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/A | /B] источник [/A | /B] [+ источник [/A | /B] [+ …]] [результат [/A | /B]]
/D — указывает на возможность создания зашифрованного файла;
/V — проверка правильности копирования файлов включена;
/N — использование коротких имён при копировании файлов (используется для совместимости с программами MS-DOS);
/Y — отключение запроса на подтверждение перезаписи существующих файлов;
/-Y — включение запроса на подтверждение перезаписи существующих файлов;
/Z — копирование сетевых файлов с возобновлением, ключ /Y можно установить через переменную среды COPYCMD;
/A — копируемый файл является текстовым файлом ASCII;
/B — копируемый файл является двоичным файлом;
источник — имена одного или нескольких копируемых файлов с их расположением;
результат — каталог и/или имя для конечных файлов.
По умолчанию осуществляется копирование файлов как двоичных «один к одному», поэтому параметр /B указывать не обязательно. Параметр /A следует использовать, если при копировании должны обрабатываться специальные символы, которые применяются в текстовых файлах.
По умолчанию команда copy требует подтверждения перезаписи существующих файлов, если не выполняется в пакетном файле.
Кроме этого, команду copy можно использовать и для объединения существующих файлов.
Примеры использования команды copy :
Копировать file1.txt в file2.txt в текущем каталоге:
Если file2.txt существует, то будет выведен запрос на перезапись файла. Не нужен подобный запрос? Тогда команда примет следующий вид:
Объединение файлов file1.txt, file2.txt и file3.txt в файл file4.txt:
Копирование всех файлов с расширением txt из текущего каталога в каталог C:\new folder.
Обратите внимание, что, если в пути к файлам встречаются пробелы, нужно использовать кавычки.
Команда copy может применяться и для копирования с использованием стандартных устройств ввода-вывода.
Копирование с устройства con (консоль) в файл C:\file.txt:
Для завершения ввода используйте Ctrl+Z или F6.
Копирование с фиктивного устройства nul в файл C:\file.txt. Данная команда создаст пустой файл:
Копировать файл на фиктивное устройство nul:
Такая команда выполнит операцию чтения и может быть использована для тестирования носителей данных.
Windows copying files cmd
Copy one or more files to another location.
Combining files
To combine files, specify a single file for the destination, but multiple files as the source. To specify more than one file use wildcards or list the files with a + in between each (file1+file2+file3)
When copying multiple files in this way the first file must exist or else the copy will fail, a workaround for this is COPY null + file1 + file2 dest1
Binary copies
«COPY /B . » will copy files in binary mode.
The /A and /B options can appear in multiple locations, with different meanings depending on location.
Before any source — they will set the default mode for all source and destination files.
After a source — they will set the mode for that source.
After the destination — they will set the mode for the destination.
Copy from the console (accept user input)
COPY CON filename.txt
Then type the input text followed by ^Z (Control key & Z)
Prompt to overwrite destination file
Under Windows 2000 and above, the default action is to prompt on overwrite unless the command is being executed from within a batch script.
To force the overwriting of destination files use the COPYCMD environment variable:
SET COPYCMD=/Y
Errorlevels
If the file(s) were successfully copied %ERRORLEVEL% = 0
If the file was not found or bad parameters given = 1
COPY will accept UNC pathnames
Copy a file in the current folder
COPY source_file.doc newfile.doc
Copy from a different folder/directory:
COPY «C:\my work\some file.doc» «D:\New docs\newfile.doc»
Specify the source only, with a wildcard will copy all the files into the current directory:
COPY «C:\my work\*.doc»
Specify the source with a wildcard and the destination as a single file, this is generally only useful with plain text files.
COPY «C:\my work\*.txt» «D:\New docs\combined.txt»
Create an empty (zero byte) file:
COPY NUL EmptyFile.txt
Quiet copy (no feedback on screen)
COPY source_file.doc newfile.doc >nul
Copy a file, but do not overwrite if the destination file already exists, this technique only works for a single file, no wildcards:
Echo n|COPY /-y c:\demo\source_file.txt c:\dir\dest.txt
COPY is an internal command.
“Success seems to be connected with action. Successful men keep moving. They make mistakes, but they don’t quit”
ROBOCOPY — Robust File and Folder Copy.
XCOPY — Copy files and folders.
MOVE — Move a file from one folder to another.
Q126457 — VERIFY ON, COPY /V, XCOPY /V commands do not compare data.
PowerShell equivalent: Copy-Item — Copy an item from one location to another.
Equivalent bash command (Linux): cp — Copy one or more files to another location.
Windows copying files cmd
Copies one or more files from one location to another.
You can also use the copy command, with different parameters, from the Recovery Console. For more information about the recovery console, see Windows Recovery Environment (Windows RE).
Syntax
Parameters
Parameter | Description |
---|---|
/d | Allows the encrypted files being copied to be saved as decrypted files at the destination. |
/v | Verifies that new files are written correctly. |
/n | Uses a short file name, if available, when copying a file with a name longer than eight characters, or with a file name extension longer than three characters. |
/y | Suppresses prompting to confirm that you want to overwrite an existing destination file. |
/-y | Prompts you to confirm that you want to overwrite an existing destination file. |
/z | Copies networked files in restartable mode. |
/a | Indicates an ASCII text file. |
/b | Indicates a binary file. |
Required. Specifies the location from which you want to copy a file or set of files. Source can consist of a drive letter and colon, a directory name, a file name, or a combination of these. | |
Required. Specifies the location to which you want to copy a file or set of files. Destination can consist of a drive letter and colon, a directory name, a file name, or a combination of these. | |
/? | Displays help at the command prompt. |
Remarks
You can copy an ASCII text file that uses an end-of-file character (CTRL+Z) to indicate the end of the file.
If /a precedes or follows a list of files on the command line, it applies to all files listed until copy encounters /b. In this case, /b applies to the file preceding /b.
The effect of /a depends on its position in the command-line string: — If /a follows source, the copy command treats the file as an ASCII file and copies data that precedes the first end-of-file character (CTRL+Z). — If /a follows destination, the copy command adds an end-of-file character (CTRL+Z) as the last character of the file.
If /b directs the command interpreter to read the number of bytes specified by the file size in the directory. /b is the default value for copy, unless copy combines files.
If /b precedes or follows a list of files on the command line, it applies to all listed files until copy encounters /a. In this case, /a applies to the file preceding /a.
The effect of /b depends on its position in the command–line string: — If /b follows source, the copy command copies the entire file, including any end-of-file character (CTRL+Z). — If /b follows destination, the copy command doesn’t add an end-of-file character (CTRL+Z).
If a write operation cannot be verified, an error message appears. Although recording errors rarely occur with the copy command , you can use /v to verify that critical data has been correctly recorded. The /v command-line option also slows down the copy command, because each sector recorded on the disk must be checked.
If /y is preset in the COPYCMD environment variable, you can override this setting by using /-y at the command line. By default, you are prompted when you replace this setting, unless the copy command is executed in a batch script.
To append files, specify a single file for destination, but multiple files for source (use wildcard characters or file1+file2+file3 format).
If the connection is lost during the copy phase (for example, if the server going offline breaks the connection), you can use copy /z to resume after the connection is re-established. The /z option also displays the percentage of the copy operation that is completed for each file.
You can substitute a device name for one or more occurrences of source or destination.
If destination is a device (for example, Com1 or Lpt1), the /b option copies data to the device in binary mode. In binary mode, copy /b copies all characters (including special characters such as CTRL+C, CTRL+S, CTRL+Z, and ENTER) to the device, as data. However, if you omit /b, the data is copied to the device in ASCII mode. In ASCII mode, special characters might cause files to combine during the copying process.
If you don’t specify a destination file, a copy is created with the same name, modified date, and modified time as the original file. The new copy is stored in the current directory on the current drive. If the source file is on the current drive and in the current directory and you do not specify a different drive or directory for the destination file, the copy command stops and displays the following error message:
If you specify more than one file in source, the copy command combines them all into a single file using the file name specified in destination. The copy command assumes the combined files are ASCII files unless you use the /b option.
To copy files that are 0 bytes long, or to copy all of a directory’s files and subdirectories, use the xcopy command.
To assign the current time and date to a file without modifying the file, use the following syntax:
Where the commas indicate that the destination parameter has been intentionally left out.
Examples
To copy a file called memo.doc to letter.doc in the current drive and ensure that an end-of-file character (CTRL+Z) is at the end of the copied file, type:
To copy a file named robin.typ from the current drive and directory to an existing directory named Birds that is located on drive C, type:
If the Birds directory doesn’t exist, the file robin.typ is copied into a file named Birds that is located in the root directory on the disk in drive C.
To combine Mar89.rpt, Apr89.rpt, and May89.rpt, which are located in the current directory, and place them in a file named Report (also in the current directory), type:
If you combine files, the copy command marks the destination file with the current date and time. If you omit destination, the files are combined and stored under the name of the first file in the list.
To combine all files in Report, when a file named Report already exists, type:
To combine all files in the current directory that have the .txt file name extension into a single file named Combined.doc, type:
To combine several binary files into one file by using wildcard characters, include /b. This prevents Windows from treating CTRL+Z as an end-of-file character. For example, type:
If you combine binary files, the resulting file might be unusable due to internal formatting.