Copy file contents linux

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:

  1. Modification time/date
  2. Access time
  3. File flags
  4. File mode
  5. User ID (UID)
  6. Group ID (GID)
  7. Access Control Lists (ACLs)
  8. 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,

  1. -a : Archive mode i.e. copy all files and directories recursively
  2. -v : Verbose mode
  3. -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

Источник

Copy File Contents Into Clipboard Without Displaying Them

This guide explains what is Clipboard, and how to copy file contents into Clipboard without displaying the contents of the file using any text viewer applications in Linux.

What is Clipboard?

You will definitely cut or copy and paste texts on your system multiple times a day. You may not have remembered how many times you copied something or haven’t ever thought about where the copied texts are actually stored. But, you should have copied/cut texts so many times. For those wondering, there is temporary place called «Clipboard» in an operating system. Clipboard is the place where the copied/cut data are kept temporarily.

Clipboard is a buffer used for short-term data storage. It is mainly used to transfer data within and between applications, via cut, copy and paste operations. Clipboard is usually temporary and unnamed place that resides in your Computer’s RAM.

The clipboards are called «Selections» and there are three types of clipboards available in X11 window system in Linux. They are:

  • PRIMARY — This is normally used when copy/paste data using Mouse middle button.
  • SECONDARY — It is not used used much, but exists.
  • CLIPBOARD — This is used for explicit copy/paste commands via Keyboard using ctrl+c and ctrl+v keys and via menu items.

There are many tools exists to manipulate the contents of clipboards. They are known as clipboard mangers and monitors. In this guide, we will discuss two command line tools namely Xclip and Xsel that are used to access clipboard contents.

Now let us get back to our main topic. How do you copy the contents of a file without actually displaying the file contents using any external applications like nano , vi editors or commands like cat ? Before I know this method, I usually open the file or display the contents of the file in standard output and then copy its contents using Mouse or Ctrl+c keys from the Keyboard. But you can do this without displaying the contents. Read on to know how.

Please note that xclip and xclip are X11 utlities. They will only work on systems that has X window system installed.

Copy file contents into Clipboard without displaying its contents, using Xclip and Xsel programs in Linux

Make sure you have installed Xclip and Xsel programs on your Linux system. They both are available in the default repositories of most Linux distributions.

To install xclip and xsel on Arch Linux and its derivatives, run:

On Debian, Ubuntu, Linux Mint:

Now let us see how to copy a file contents using Xclip and Xsel programs. For the purpose of this guide, I use text file named ostechnix.txt and the contents of this file is given below:

To copy the contents of ostechnix.txt file into clipboard, without displaying its contents, run:

Or shortly use this:

Copy file Contents into Clipboard without displaying them using Xclip in Linux

Xclip has now copied the contents of ostechnix.txt file to the clipboard. You can paste the copied data to anywhere using Ctrl+p keys or selecting the paste option from menu items or right click context menu.

You can also copy the contents of a file into clipboard using Xsel command like below:

Or, shortly use this:

Copy file contents into Clipboard without displaying them using Xsel in Linux

To save a few strokes, you can create a script named «send2clip» with the following lines:

Use any name of your choice for this script. Then make the script executable:

Now pass any file as an argument to copy its contents to clipboard. For example, the following command will copy the contents of ostechnix.txt file:

Copy Linux and Unix commands output to clipboard

Not just the output of files, you can also send the output of any Linux and Unix commands to clipboard using Xclip and Xsel programs.

To copy a Linux command’s output into clipboard using Xclip and Xsel , run:

Example:

Copy Linux and Unix commands output into clipboard

The above commands will copy your Linux system Kernel details into clipboard.

To learn more about Xclip and Xsel commands, refer the man pages.

Источник

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

Источник

Читайте также:  Install hyper v windows core
Оцените статью