- How to Copy and Paste Text, Files and Folders in Linux Terminal
- Copy and Paste Text
- Copy and Paste a Single File
- Copy and Paste a Folder and Its Contents
- Copy and Paste Multiple Files
- Copy and Paste All Files of the Same Type
- Move a File or Folder
- Копирование файлов в Linux
- Утилита копирования файлов cp
- Синтаксис и опции
- Примеры копирования файлов в linux
- Копирование файлов по регулярным выражениям в Linux
- Копирование содержимого файлов в Linux
- Специальное копирование файлов в Linux с помощью tar
- Выводы
- How to Copy Paste in Linux Terminal [For Absolute Beginners]
- How to copy paste text and commands in the Linux terminal
- Method 1: Using keyboard shortcuts for copy pasting in the terminal
- Method 2: Using right click context menu for copy pasting in the terminal
- Method 3: Using mouse to copy paste in Linux terminal
- There is no universal key shortcuts for copy paste in the Linux terminal. Here’s why!
- Why Linux terminals do not use the ‘universal’ Ctrl+C and Ctrl+V for
How to Copy and Paste Text, Files and Folders in Linux Terminal
Copying and pasting is one of the most used actions on a computer. While it is easy to do so with the Ctrl + C and Ctrl + V keyboard shortcuts, on the Linux terminal it is not so straightforward. You have several options to get the job done. Here is how you can copy and paste text, files and directories in Linux terminal.
Also read: How to Easily Rename Files in Linux
Copy and Paste Text
If you just want to copy a piece of text in the terminal, all you need to do is highlight it with your mouse, then press Ctrl + Shift + C to copy.
To paste it where the cursor is, use the keyboard shortcut Ctrl + Shift + V .
The Paste shortcut also applies when you copy a section of text from a Word document (or any other application) and want to paste it in the terminal. For example, you can copy a command from a web page in your browser and use the Ctrl + Shift + V shortcut to paste it in the terminal.
Copy and Paste a Single File
Any time you want to copy a file or folder in the Linux command line, the above keyboard shortcut won’t work. You have to use the cp command. cp is shorthand for copy. The syntax is simple, too. Use cp followed by the file you want to copy and the destination where you want it moved.
That, of course, assumes that your file is in the same directory you’re working out of. You can specify both.
You also have the option of renaming your file while copying it. Specify the new name in the destination.
Copy and Paste a Folder and Its Contents
In order to copy a folder and its contents, you’re going to need to tell the cp command to copy recursively. That’s simple enough with the -r flag.
All the rest of your syntax is exactly the same. The -r flag serves to tell cp that it’s working with a directory and should copy its contents.
If you want the paste action to overwrite existing files, you can add the -f flag:
Also read: How to Compress Files with zstd Utility in Linux
Copy and Paste Multiple Files
You can also copy multiple files. The Linux command line lets you target multiple items at once with brackets <> . You can use them to list the names of each file to be copied separated by commas.
All three files of differing file types will be copied to the Documents directory.
Copy and Paste All Files of the Same Type
If you have a ton of files of the same type to copy, you can use the wildcard character * . The asterisk/wildcard tells the Linux command line to accept absolutely anything in that place. So, if you tell Linux to copy *.jpg , it’ll copy all JPG files, regardless of the name or whatever comes before the .jpg part.
If you want to use multiple file types, say JPG and PNG, you can use the brackets from before.
Move a File or Folder
If you came here looking to move a file from one place to another without making a duplicate, you can do that easily too, but moving a file requires the mv command. The syntax is very similar to cp.
Similarly, you can also rename it.
There is one major difference, though. You don’t need the -r flag to move a whole folder.
That’s all there is to it. You’re ready to start copying and moving your files from the command line. You can see that the command line way can be very efficient in some situations.
Want more pointers on the Linux command line? Here’s how to check sudo history or find out what the chmod 777 command does to your file permission.
Image credit: Copy – Paste by DepositPhotos
Источник
Копирование файлов в 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 9 -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 Paste in Linux Terminal [For Absolute Beginners]
Last updated October 29, 2020 By Abhishek Prakash 27 Comments
I have been using Linux for a decade now and this is why sometimes I take things for granted.
Copy pasting in the Linux terminal is one of such things.
I thought everyone already knew this until one of the It’s FOSS readers asked me this question. I gave the following suggestion to the Ubuntu user:
Use Ctrl+Insert or Ctrl+Shift+C for copying and Shift+Insert or Ctrl+Shift+V for pasting text in the terminal in Ubuntu. Right click and selecting the copy/paste option from the context menu is also an option.
I thought of elaborating on this topic specially when there is no single universal way of copy and paste in the Linux terminal.
How to copy paste text and commands in the Linux terminal
There are several ways to do this.
Method 1: Using keyboard shortcuts for copy pasting in the terminal
On Ubuntu and many other Linux distributions, you can use Ctrl+Insert or Ctrl+shift+C for copying text and Shift+Insert or Ctrl+shift+V for pasting text in the terminal.
The copy pasting also works for the external sources. If you copy a command example from It’s FOSS website (using the generic Ctrl+C keys), you can paste this command into the terminal using the Ctrl+Shift+V into the terminal.
Similarly, you can use Ctrl+shift+C to copy text from the terminal and then use it to paste in a text editor or web browser using the regular Ctrl+V shortcut.
Basically, when you are interacting with the Linux terminal, you use the Ctrl+Shift+C/V for copy-pasting.
Method 2: Using right click context menu for copy pasting in the terminal
Another way of copying and pasting in the terminal is by using the right click context menu.
Select the text in the terminal, right click and select Copy. Similarly, to paste the selected text, right click and select Paste.
Method 3: Using mouse to copy paste in Linux terminal
Another way to copy paste in Linux terminal is by using only the mouse.
You can select the text you want to copy and then press the middle mouse button (scrolling wheel) to paste the copied text.
Please keep in mind that these methods may not work in all the Linux distributions for a specific reason that I explain in the next section.
There is no universal key shortcuts for copy paste in the Linux terminal. Here’s why!
The keybindings for copy-pasting are dependent on the terminal emulator (commonly known as terminal) you are using.
If you didn’t know that already terminal is just an application and you can install other terminals like Guake or Terminator.
Different terminal applications may have their own keybindings for copying and pasting like Alt+C/V or Ctrl+Alt+C/V.
Most Linux terminals use the Ctrl+Shift+C/V keys but if it doesn’t work for you, you may try other key combinations or configure the keys from the preferences of the terminal emulator.
Quick word about Putty
If you use Putty on Linux or Windows, it uses an entire different keybindings. In Putty, selecting a text automatically copies it and you can paste it using right click.
Why Linux terminals do not use the ‘universal’ Ctrl+C and Ctrl+V for
No Linux terminal will give you Ctrl+C for copying the text. This is because by default Ctrl+C keybinding is used for sending an interrupt signal to the command running in foreground. This usually stops the running command.
This behavior has been existing long before Ctrl+C and Ctrl+V started being used for copy-pasting text.
Since the Ctrl+C keys are ‘reserved’ for stopping a command, it cannot be used for copying.
Used Ctrl+S and hanged the terminal?
Most of us use Ctrl+S keys to save changes made to text, images etc. This key is almost universal for saving same as Ctrl+C is for copying.
However, if you enter Ctrl+S in Linux terminal, it will freeze the terminal. No need to close the terminal and start it again. You can use Ctrl+Q to unfreeze the terminal.
Ctrl+S and Ctrl+Q are shortcut keys for flow control.
I know this is elementary for the Sherlock Holmes of the Linux world but it could still be useful to the Watsons.
New or not, you may always use shortcuts in Linux terminal to make your life easier.
Like what you read? Please share it with others.
Источник