Linux copy several files

Копирование файлов в 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 выполнит замену на новую версию:

Читайте также:  Нет соединения скайп windows 10

Сp также поддерживает специальные символы замены * и ?. Например, следующая команда скопирует все файлы, начинающиеся на test:

Если нужно применить более сложные регулярные выражения, придётся комбинировать утилиту cp с find или egrep.

В случае, если важно сохранить права доступа к файлу и его владельца, нужно использовать опцию -p:

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

Будет создан файл с таким же именем и расширением .bak

По умолчанию в cp не отображается прогресс копирования файла, что очень неудобно при работе с большими файлами, но его можно легко посмотреть с помощью утилиты cv.

Копирование файлов по регулярным выражениям в Linux

В утилите find можно применять различные условия и регулярные выражения для поиска файлов. Я уже немного писал о ней в статье как найти новые файлы в Linux. Мы можем скопировать все найденные с помощью find файлы, вызвав для каждого из них команду cp. Например, копируем все файлы в текущей директории, содержащие в имени только цифры:

find . -name 6 -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 в целом. Как видите, в терминале это выполняется намного быстрее и эффективнее, чем с помощью графического интерфейса, если помнить нужные команды. Если у вас остались вопросы, спрашивайте в комментариях!

Источник

How to Copy files and folders in Linux

Being a Linux user, copying files and directories is one of the most common tasks.

Linux users don’t spend a day without using the cp (copy) command according to my personal experience. cp command is used to copy a single file or group of files or directory.

Читайте также:  Установка линукс кодачи с флешки

To perform the copy operation, you must have at least read permission in the source file and write permission in the target directory.

In this article, we will explain how to use the cp command.

To perform remote file copy, use the commands such as rsync command or scp command or pscp command.

What is cp command?

‘cp’ command is one of the basic and most widely used Linux commands for copying files and directories from one location to another.

When copying files from source to destination, the source file remains the same and the target file may have the same or different name.

Common syntax for cp command:

Common options for cp command:

Options Description
-v Verbose mode (Show progress)
-r/R Copy directories recursively
-n Don’t overwrite an existing file
-d Copy a link file
-i Prompt before overwrite
-p Preserve the specified attributes
-b Make a backup of each existing destination file

To demonstrate file copy operation in detail, we will be performing a copy operation between user1 and user2 .

1) Copying files with cp command

Use the following command to copy a file from one location to another.

In the following example, we will copy the source file “/home/user1/cp-demo.txt” to the target directory “/home/user2” with the same name:

You can check whether the specific file is copied to the target directory using the ls command as shown below:

2) Copying files with a different name

Use the following command to copy a file from one place to another with a different name. You need to give a new name to the target file.

In the following example, we will copy a file named “/home/user1/cp-demo.txt” to the target directory with a new name “/home/user2/cp-demo11.txt” :

Use the ls command to verify this:

3) Copying multiple files in Linux

The following cp command copies multiple files from one location to another.

In this example, we will copy the following three files named “cp-demo.txt, cp-demo-1.txt and cp-demo-9.txt” to the target.

No additional option is required to copy multiple files, and the file name(s) must be separated with a space as shown below:

Use the ls command to verify the copied files. You should see them in the target directory as shown below:

4) How to copy directories recursively

To copy a directory recursively from one location to another, use the -r/R option with the cp command. It copies everything, including all its files and subdirectories.

In the following example, we will copy the ‘/home/user1/cp-demo-folder’ directory to ‘/home/user2/’ and the target directory name will remain the same:

Use the ls command to verify the outcome. You should see them in the target directory as shown below:

5) Copying multiple directories recursively

Use the following command to copy multiple directories at once. In the following example, we will copy the public_html & public_ftp folders to the target directory named /home/2daygeek/cp-test.

Output can be verified using the ls command:

6) Copying specific format files in Linux

Sometimes you may have to copy files with a specific extension for a certain purpose. If so, you should use the cp command with the «wildcard (*)» option and the file extension name.

In the following example, we will copy all the files containing the *.sh extension from the source to the target directory. Similarly, you can copy any file extensions such as .jpg, .png, .txt, .php, and .html.

This can be verified using the ls command:

7) Copying all files at once in Linux

To copy all the files except the directory from one location to another, use the following cp command with wildcard (*) option.

cp command excludes directories by default, and the -r option must be added to copy them.

In this example, we will copy all the files from ‘/home/user1/’ to ‘/home/user2′ :

Verify the output using the ls command as shown below:

8) How to copy hidden files (‘.’ dot files) in Linux

By default, the cp command does not copy “dot (.)” or ‘hidden’ files in Linux.

Use the following command to copy all types of files, including link files (soft link or hard link), folders and hidden or dot files from source to destination.

This example is very useful to copy user’s home directory which has several hidden files:

You can verify this by using the ls command with the “-a” option:

9) Backup the file with cp command

cp command allows you to backup the file if the same file name exists in the target directory using the —backup option.

In this example, we will copy the /home/user1/passwd-up.sh file to the target directory /home/user2/.

It will backup the “passwd-up.sh” file in the target directory during the copy operation, if you say “yes” when you see the message below:

It adds the “Tilde (

)” symbol at the end of the old file, the same can be verified in the following output.

10) Copying files with attributes

By default, Linux replaces file attributes such as username, group name, date and time when copying files from a user, and does not carry the original file attributes.

To preserve the original attributes of the files, use the -p option with the cp command.

Upon querying we can see that the file “service-1.sh” has retained its original attributes as shown below:

11) How to avoid file overwriting with cp command?

When copying a file, use the -n option with the cp command to avoid overwriting an existing file.

It will only copy the source file, if the target directory does not have a file with the same name. If a duplicate file exists in the target, then the command will run, but won’t make any changes:

Upon querying using the ls command, it can be seen that no action is taken against the file because it still has the old attributes, which can be seen in the above example (refer section 10):

12) Prompting confirmation with cp command

Use the -i option with the cp command to prompt for confirmation before overwriting the file, in case the file exists in the target location.

The following example prompts for confirmation when copying the “cp-demo-9.txt” file because the file already exists in the target directory:

By default, the cp command excludes link files while performing the copy operation. Use the -d option with the cp command to copy the link files as shown below:

It has been successfully copied, and the soft link file can be found in the below output:

Conclusion:

In this tutorial, we have demonstrated 13 methods that are widely used by the Linux administrators in their daily operations. If you would like to explore other options, please visit the man page of the cp command by using the following command:

Источник

Читайте также:  Hp mouse control center windows 10
Оцените статью