- How To Copy Command Output To Linux Clipboard Directly
- A note about Linux / UNIX X Server CLIPBOARD
- xclip – Linux / UNIX Command line clipboard grabber
- Installing xclip under Debian / Ubuntu Linux To copy command output to clipboard
- How to xclip under Red hat / CentOS / RHEL / Fedora Linux
- How do I use the xclip command for clipboard copy and paste?
- Работа с буфером обмена в Linux: теория и практика
- Совсем немного теории
- Практика
- Скрипты
- Что дальше?
- Copy File Contents Into Clipboard Without Displaying Them
- What is Clipboard?
- Copy file contents into Clipboard without displaying its contents, using Xclip and Xsel programs in Linux
- Copy Linux and Unix commands output to clipboard
- What is the command line equivalent of copying a file to clipboard?
- 4 Answers 4
- Linux — copy/cut file into clipboard
- 3 Answers 3
How To Copy Command Output To Linux Clipboard Directly
H ow do I copy the output of a command to the Linux Gnome clipboard? How can I send files directly to X Windows clipboard from a shell prompt? What is the best way to insert command line output or files contains into the clipboard under Linux?
We can copy command line output to X Windows clipboard directly using the xclip command. You can read from a standard input device such as a keyboard. However, one can use files and pipes too. We can feed this data as an X selection for pasting into any X applications such as GIMP, gedit, OpenOffice, Firefox or an email client. You can also print the current X selection to standard out (screen or printer) from a shell prompt. Let us see how to use the xclip command/xsel command as a copy command for the clipboard.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | xclip and xsel utilities on Linux |
Est. reading time | 6 minutes |
A note about Linux / UNIX X Server CLIPBOARD
There are 3 clipboards maintained by the X server as follows:
- PRIMARY: The PRIMARY selection is conventionally used to implement copying and pasting via the middle mouse button. xclip command use this by default. So you need to hit middle button to paste data.
- SECONDARY: This is less frequently used by X application. You need to use XA_SECONDARY constant to select this clipboard.
- CLIPBOARD: Same as SECONDARY, use XA_CLIPBOARD constant to select clipboard.
xclip – Linux / UNIX Command line clipboard grabber
You can install xclip using any one of the following method:
Installing xclip under Debian / Ubuntu Linux To copy command output to clipboard
Type the following apt command/apt-get command at shell prompt:
$ sudo apt-get install xclip
How to xclip under Red hat / CentOS / RHEL / Fedora Linux
Type the following dnf command/yum command at shell prompt (make sure 3rd party EPEL repos are activated):
# yum install xclip
How do I use the xclip command for clipboard copy and paste?
Let us copy the output of the following command to the Linux clipboard. The syntax is:
command | xclip
command | xclip -i
To paste selection to standard out or pipe, use the following command again:
xclip -o
xclip -o | myapp1 -arg1
Источник
Работа с буфером обмена в Linux: теория и практика
Совсем немного теории
Исторически сложилось так, что в X Window System (X11, — оконная система для Linux, UNIX) существует два буфера обмена.
Один из них (clipboard) похож на буфер обмена в Windows — при нажатии на Ctrl+Insert или Ctrl+C выделенный фрагмент (текст, картинка, файл) копируется в буфер обмена, а при нажатии на Shift+Insert (или Ctrl+V) — вставляется из него. Следует заметить, что во многих программах эти сочетания зарезервированы для иных целей и приходится пользоваться другими — например, в терминале сочетание Ctrl+C используется для завершения процесса, а для работы с буфером обмена используются сочетания Ctrl+Shift+C для копирования и Ctrl+Shift+V для вставки.
Второй буфер (primary) является специфичным для оконной системы X11. Выделенный текст незамедлительно попадает в буфер primary, и для того, чтобы вставить скопированный текст, достаточно лишь нажать среднюю кнопку мышки (колёсико). У кого в наличии не имеется трёхкнопочной мышки, а так же владельцам ноутбуков с тачпадами следует одновременно нажать левую и правую кнопки мышки для вставки текста.
Обычно эти буферы не связаны друг с другом (некоторые программы некорректно их обрабатывают и считают, что это один и тот же буфер обмена). Следовательно, хранящиеся в них данные не влияют друг на друга, что, несомненно, крайне удобно. Следует заметить, что при закрытии программы, из которой были скопированы данные, содержимое буфера обмена теряется.
Практика
Для решения проблемы утери данных из буфера обмена при закрытии программы существует сторонний софт. Например, Clipboard Daemon. Этот маленький демон держит содержимое буфера обмена в памяти независимо от того, было ли закрыто приложение, из которого скопированы данные.
Для более комфортной работы с буфером обмена существует целый ряд программ:
- Parcellite — многообещаюший менеджер буфера обмена на GTK
- glipper — для Gnome
- klipper — для KDE
- wmcliphist — для Window Maker
- и куча других (в том числе для Windows, Mac OS и прочего).
Эти программы позволяют существенно облегчить работу — они хранят историю содержимого буферов обмена — в любой момент можно вернуться к любому из предыдущих состояний (в пределах разумного, конечно, — этот предел, как водится, устанавливается в настройках) и воспользоваться им =)
Существует так же весьма и весьма полезная в умелых руках утилита под названием xclip, предназначенная для работы с буферами обмена из командной строки. Копирование и вставка текста осуществляется простыми командами, что позволяет использовать её в различного рода вспомогательных скриптах, примеры которых я продемонстрирую ниже.
К сожалению, официальная версия xclip у меня с кириллицей корректно не заработала, несмотря на то, что я собирал последнюю версию. Поэтому я предлагаю скачать и собрать версию xclip для дистрибутива Alt Linux.
Скрипты
xclip -o | sed -n 1p | xargs firefox -new-tab
Он открывает новую вкладку в Firefox с адресом, который находится в буфере обмена (очень часто нужно открыть ссылку в виде простого текста — например, если ссылка встретилась в текстовом редакторе — приходится её копировать, открывать вкладку в браузере и вставлять скопированный адрес. Скрипт делает всё за вас ;). Я назначил его на сочетание Win+F.
Благодаря тому, что буфер обмена является универсальной для ОС сущностью, эти скрипты будет работать везде — от терминала и текстового редактора до самого Firefox’а (впрочем, желающие могут настроить этот же скрипт и для альтернативных браузеров. Назначить скриптам сочетание кнопок можно как с помощью вашего windows manager’а (например, gconf-editor для Gnome), так и с помощью сторонних программ, таких как xmodmap или actkbd.
Что дальше?
Да что угодно =) Можно переводить фразы, выделенные мышкой, можно копировать их в программу для заметок — всё зависит от вашей фантазии и потребностей. Конечно, для таких вещей могут существовать отдельные программы, но такие вот самописные скрипты, на мой взгляд, для любого пользователя окажутся удобнее всего — linux тем и хорош, что можно всё, абсолютно всё настроить под себя и для себя.
Update: добавлена ссылка на менеджер буфера обмена Parcellite — спасибо хабрапользователю drujebober
Update 2: по просьбе хабраюзера dimaka добавил скрипты для перевода:
+ ! t t
f Copy full filename into clipboard
echo -n %d/%f | xclip
_________
Текст подготовлен в редакторе VIM 😉
Источник
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.
Источник
What is the command line equivalent of copying a file to clipboard?
What is the command line equivalent to pressing CTRL+C over a file in the file manager so that the file (not the filename) is copied to the clipboard?
A situation where this can be useful and fast, for example, is when you want to copy to the clipboard a file from the directory you are in the terminal to quickly paste the file in the directory you are in the file manager. There are others.
4 Answers 4
When you press Ctrl-C over a file in the file manager, the file’s contents IS NOT copied to the clipboard. A simple test: select a file in file manager, press Ctrl-C, open a text editor, press Ctrl-V. The result is not file’s contents but its full path.
In reality the situation is a bit more complicated because you can’t do the opposite — copy a list of filenames from a text editor and paste them into file manager.
To copy some data from command line to X11 clipboard you can use xclip command, which can be installed with
to copy contents of a file or output of some command to clipboard use
the text can be then pasted somewhere using middle mouse button (this is called «primary selection buffer»).
If you want to copy data to the «clipboard» selection, so it can be pasted into an application with Ctrl-V, you can do
To be able to copy files from the command line and paste them in a file manager, you need to specify a correct «target atom» so the file manager recognizes the data in the clipboard, and also provide the data in correct format — luckily, in case of copying files in a file manager it’s just a list of absolute filenames, each on a new line, something which is easy to generate using find command:
(at least this works for me in KDE). Now you can wrap into a small script which you can call, say, cb :
then you put it in
/bin , set executable bit on it and use it like this:
Источник
Linux — copy/cut file into clipboard
I was wondering if it is possible to copy or cut a file into the clipboard and then paste it to another directory later on. I did a quick research and only found information on how to copy the content of a file into the clipboard, but not the file itself.
3 Answers 3
When you press Ctrl-C over a file in the file manager, the file’s contents IS NOT copied to the clipboard. A simple test: select a file in file manager, press Ctrl-C, open a text editor, press Ctrl-V. The result is not file’s contents but its full path.
In reality the situation is a bit more complicated because you can’t do the opposite — copy a list of filenames from a text editor and paste them into file manager.
To copy some data from command line to X11 clipboard you can use xclip command, which can be installed with
to copy contents of a file or output of some command to clipboard use
the text can be then pasted somewhere using middle mouse button (this is called «primary selection buffer»).
If you want to copy data to the «clipboard» selection, so it can be pasted into an application with Ctrl-V, you can do
To be able to copy files from the command line and paste them in a file manager, you need to specify a correct «target atom» so the file manager recognizes the data in the clipboard, and also provide the data in correct format — luckily, in case of copying files in a file manager it’s just a list of absolute filenames, each on a new line, something which is easy to generate using find command:
(at least this works for me in KDE). Now you can wrap into a small script which you can call, say, cb :
then you put it in
/bin , set executable bit on it and use it like this:
Источник