- Linux Copy File Command [ cp Command Examples ]
- cp Command Syntax
- Linux Copy File Examples
- Copy a file to another directory
- Verbose option
- Preserve file attributes
- Copying all files
- Recursive copy
- Linux copy file command with interactive option
- Verbose output with cp command
- Conclusion
- How to copy one file contents to another file in Linux
- Copy one file contents to another file in Linux
- Linux copy file to another file
- Copy content of one file to another file
- Conclusion
- Thread: copy only files that have changed?
- copy only files that have changed?
- Re: copy only files that have changed?
- Копирование файлов в Linux
- Утилита копирования файлов cp
- Синтаксис и опции
- Примеры копирования файлов в linux
- Копирование файлов по регулярным выражениям в Linux
- Копирование содержимого файлов в Linux
- Специальное копирование файлов в Linux с помощью tar
- Выводы
Linux Copy File Command [ cp Command Examples ]
cp Command Syntax
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Terminal app/Shell prompt |
Est. reading time | 3 mintues |
The syntax is as follows to copy files and directories using the cp command:
cp SOURCE DEST
cp SOURCE DIRECTORY
cp SOURCE1 SOURCE2 SOURCE3 SOURCEn DIRECTORY
cp [OPTION] SOURCE DEST
cp [OPTION] SOURCE DIRECTORY
Where,
- In the first and second syntax you copy SOURCE file to DEST file or DIRECTORY.
- In the third syntax you copy multiple SOURCE(s) (files) to DIRECTORY.
Note: You need to type the cp command at the dollar sign ($) prompt. This prompt means that the shell is ready to accept your typed commands. Do not type the dollar ($) sign. You need to open the Terminal app to use cp command on a Linux.
Linux Copy File Examples
To make a copy of a file called file.doc in the current directory as newfile.doc, enter:
$ cp file.doc newfile.doc
$ ls -l *.doc
Sample outputs:
You can copy multiple files simultaneously into another directory. In this example, copy the files named main.c, demo.h and lib.c into a directory named backup:
$ cp main.c demo.h libc. backup
If backup is located in /home/project, enter:
$ cp main.c demo.h libc. /home/project backup
Copy a file to another directory
To copy a file from your current directory into another directory called /tmp/, enter:
$ cp filename /tmp
$ ls /tmp/filename
$ cd /tmp
$ ls
$ rm filename
Verbose option
To see files as they are copied pass the -v option as follows to the cp command:
Preserve file attributes
To copy a file to a new file and preserve the modification date, time, and access control list associated with the source file, enter:
$ cp -p file.txt /dir1/dir2/
$ cp -p filename /path/to/new/location/myfile
This option ( -p ) forces cp to preserve the following attributes of each source file in the copy as allowed by permissions:
- Modification time/date
- Access time
- File flags
- File mode
- User ID (UID)
- Group ID (GID)
- Access Control Lists (ACLs)
- Extended Attributes (EAs)
Copying all files
The star wildcard represents anything i.e. all files. To copy all the files in a directory to a new directory, enter:
$ cp * /home/tom/backup
The star wildcard represents anything whose name ends with the .doc extension. So, to copy all the document files (*.doc) in a directory to a new directory, enter:
$ cp *.doc /home/tom/backup
Recursive copy
To copy a directory, including all its files and subdirectories, to another directory, enter (copy directories recursively):
$ cp -R * /home/tom/backup
Linux copy file command with interactive option
You can get prompt before overwriting file. For example, if it is desired to make a copy of a file called foo and call it bar and if a file named bar already exists, the following would prompt the user prior to replacing any files with identical names:
cp -i foo bar
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Verbose output with cp command
If you pass the -v to the cp, it makes tells about what is going on. That is verbose output:
cp -v file1 file2
cp -avr dir2 /backups/
Conclusion
This page explained cp command that is used for copying files under Linux and Unix-like systems. For more info see man pages: ls(1).
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to copy one file contents to another file in Linux
Copy one file contents to another file in Linux
The cp commands basic syntax is:
cp file_name new_file_name
cp [options] file_name new_file_name
cp original_name new_name
Please note that when a copy is made of a file, the copy must have a different name than the original. For example, the following is a valid example:
cp file1 file2
However, the following would fail:
cp nixcraft.txt nixcraft.txt
Sample outputs:
However, a file named nixcraft.txt could be copied with the same name into another directory:
cp -v nixcraft.txt /tmp/
File names are case sensitive too. It means following example should work:
cp nixcraft.txt NIXCRAFT.txt
ls -l nixcraft.txt NIXCRAFT.txt
Sample outputs:
Linux copy file to another file
Let us create a new file in Linux named foo.txt:
echo «This is a test» > foo.txt
Next copy foo.txt as bar.txt, run:
cp foo.txt bar.txt
Verify it with help of ls command:
ls -l foo.txt
ls -l bar.txt
To see cp command progress and verbose output, pass the -v command option to cp:
cp -v foo.txt bar.txt
Update the original foo.txt:
echo «Another line» >> foo.txt
Use the cat command to see both files:
cat foo.txt
cat bar.txt
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Copy content of one file to another file
Say you want to copy all files from /home/vivek/project/ to /home/vivek/backups/, run:
cp -av /home/vivek/project/ /home/vivek/backups/
Now, we can make changes in /home/vivek/project/ directory.
Where,
- -a : Archive mode i.e. copy all files and directories recursively
- -v : Verbose mode
- -r : Recursive mode in Linux for cp command
Conclusion
Writing contents of a file to another file is easy in Linux. Simply use:
cp -v filename newname
For more information see cp command man page by typing the following [nixmd name=”man”]:
man cp
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Thread: copy only files that have changed?
Thread Tools
Display
copy only files that have changed?
Is there a way to copy only files that have changed since the last backup?
I know the -u switch will update existing files but that is not what I want to do. I’m working on a web site & I have about 20 or 30 different files that I constantly back up into a new folder that is named by the date & time. I use a shell script that makes it easy to do but I can’t figure out how to only backup the files I’ve worked on since the last backup. I may only work on one or two of the files at a time but since they get backed up into an empty directory the -u switch still copies all the files. In DOS xcopy there is a switch that will do this but I can’t find anything in Linux that will. I find it hard to believe that MSDOS has got something better from the command line than Linux. Surely I must be missing something, right?
I wish I knew what I used to know before I knew what I didn’t know.
Re: copy only files that have changed?
That is basically what rsync do best. For example, the first time you run this:
It will only copy the files that have changed.
Does that help? There are a lot of more options. Tell us if you need more help customizing it.
EDIT: some of the options include a way to access a backup that you already have done, so you can compare the source with the backup and only copy the changed files into a different directory.
Last edited by papibe; December 14th, 2011 at 08:27 AM .
Источник
Копирование файлов в Linux
Копирование файлов — одна из задач, наиболее часто возникающих перед пользователями персонального компьютера. Конечно, можно открыть файловый менеджер, войти в нужную папку и скопировать файл с помощью контекстного меню — тут не о чем говорить. Но в этой статье я хотел бы рассмотреть копирование файлов в Linux с помощью терминала.
Не всегда есть доступ к файловому менеджеру: из-за различных поломок графическая оболочка на домашнем компьютере может быть недоступна, а на серверах используется только консольный интерфейс. К тому же копирование файлов Ubuntu через терминал намного эффективнее, и вы сами в этом убедитесь. Сегодня мы рассмотрим не только обычное копирование командой cp Linux, но и не совсем обычное: с помощью tar и find.
Утилита копирования файлов cp
Название утилиты cp — это сокращение от Copy, что означает копировать. Утилита позволяет полностью копировать файлы и директории.
Синтаксис и опции
Общий синтаксис cp выглядит вот так:
$ cp опции файл-источник файл-приемник
$ cp опции файл-источник директория-приемник/
После выполнения команды файл-источник будет полностью перенесен в файл-приемник. Если в конце указан слэш, файл будет записан в заданную директорию с оригинальным именем.
Утилита имеет несколько интересных опций, которые могут сильно помочь при нестандартных задачах копирования, поэтому давайте их рассмотрим:
- —attributes-only — не копировать содержимое файла, а только флаги доступа и владельца;
- -f, —force — перезаписывать существующие файлы;
- -i, —interactive — спрашивать, нужно ли перезаписывать существующие файлы;
- -L — копировать не символические ссылки, а то, на что они указывают;
- -n — не перезаписывать существующие файлы;
- -P — не следовать символическим ссылкам;
- -r — копировать папку Linux рекурсивно;
- -s — не выполнять копирование файлов в Linux, а создавать символические ссылки;
- -u — скопировать файл, только если он был изменён;
- -x — не выходить за пределы этой файловой системы;
- -p — сохранять владельца, временные метки и флаги доступа при копировании;
- -t — считать файл-приемник директорией и копировать файл-источник в эту директорию.
Примеры копирования файлов в linux
Теперь, когда вы знаете основные опции, можно перейти к практике. Например, мы хотим скопировать некую картинку из домашней папки в подкаталог pictures:
Или можем явно указать имя новой картинки:
Копирование папок осуществляется с помощью ключа -r:
После выполнения этой команды копирования
/папка будет скопирована в папку
/Документы. Главное, не забывайте поставить слэш в конце выражения или использовать опцию -t. Иначе папка
/документы будет перезаписана.
По умолчанию команда cp Linux перезаписывает существующие файлы или папки, но можно заставить утилиту спрашивать, нужно ли перезаписывать каждый файл, если вы не уверены в правильности составления команды:
Есть и противоположная опция -n, означающая «никогда не перезаписывать существующие файлы».
Опция -u полезна в следующем случае: вы знаете или предполагаете, что в директории, куда копируется файл, есть старая его версия, тогда оператор -u выполнит замену на новую версию:
Сp также поддерживает специальные символы замены * и ?. Например, следующая команда скопирует все файлы, начинающиеся на test:
Если нужно применить более сложные регулярные выражения, придётся комбинировать утилиту cp с find или egrep.
В случае, если важно сохранить права доступа к файлу и его владельца, нужно использовать опцию -p:
Для упрощения использования команды можно применять синтаксис фигурных скобок. Например, чтобы создать резервную копию файла, выполните:
Будет создан файл с таким же именем и расширением .bak
По умолчанию в cp не отображается прогресс копирования файла, что очень неудобно при работе с большими файлами, но его можно легко посмотреть с помощью утилиты cv.
Копирование файлов по регулярным выражениям в Linux
В утилите find можно применять различные условия и регулярные выражения для поиска файлов. Я уже немного писал о ней в статье как найти новые файлы в Linux. Мы можем скопировать все найденные с помощью find файлы, вызвав для каждого из них команду cp. Например, копируем все файлы в текущей директории, содержащие в имени только цифры:
find . -name 8 -exec cp <>
Здесь точка указывает на текущую директорию, а параметр name задает регулярное выражение. Параметром exec мы задаем, какую команду нужно выполнить для обнаруженных файлов. Символ <> — подставляет имя каждого файла.
Но не find‘ом единым такое делается. То же самое можно получить, запросив список файлов директории в ls, отфильтровав его по регулярному выражению egrep и передав имена файлов по очереди в cp с помощью xargs:
/ | egrep ‘[a-zA-Z]’ | xargs cp -t
Это не совсем удобный способ копировать файлы Linux, но всё же он возможен. Будут скопированы все файлы из домашней директории, содержащие в имени только английские буквы.
Копирование содержимого файлов в Linux
Вы можете не только копировать сами файлы, но и управлять их содержимым. Например, склеить несколько файлов в один или разрезать файл на несколько частей. Утилита cat используется для вывода содержимого файла, в комбинации с операторами перенаправления вывода Bash вы можете выполнять копирование содержимого файла Linux в другой файл. Например:
cat файл1 > файл2
Если файл был не пустым, он будет перезаписан. Или мы можем склеить два отдельных файла в один:
cat файл1 файл2 > файл3
Специальное копирование файлов в Linux с помощью tar
Linux интересен тем, что позволяет выполнять одно и то же действие различными путями. Копирование в Linux тоже может быть выполнено не только с помощью cp. При переносе системных файлов в другой каталог, резервном копировании системных файлов и т.д. важно чтобы сохранились атрибуты, значения владельцев файлов и символические ссылки как они есть без какой-либо модификации.
Утилита cp тоже может справиться с такой задачей? если указать опцию -p, но можно использовать утилиту архивации tar. Мы не будем создавать никаких файлов архивов, а построим туннель. Первая часть команды пакует файл и отправляет на стандартный вывод, а другая сразу же распаковывает в нужную папку:
tar cf — /var | ( cd /mnt/var && tar xvf — )
Здесь мы полностью копируем содержимое папки /var в папку /mnt/var. Так вы можете копировать папку Linux, причём абсолютно любую или даже целую операционную систему.
Выводы
Теперь вы знаете, как выполняется копирование файлов Ubuntu и в Linux в целом. Как видите, в терминале это выполняется намного быстрее и эффективнее, чем с помощью графического интерфейса, если помнить нужные команды. Если у вас остались вопросы, спрашивайте в комментариях!
Источник