Linux copy to buffer

Работа с буфером обмена в 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 тем и хорош, что можно всё, абсолютно всё настроить под себя и для себя.

Читайте также:  Как сделать сетевую папку между компьютерами windows

Update: добавлена ссылка на менеджер буфера обмена Parcellite — спасибо хабрапользователю drujebober

Update 2: по просьбе хабраюзера dimaka добавил скрипты для перевода:

+ ! t t
f Copy full filename into clipboard
echo -n %d/%f | xclip

_________
Текст подготовлен в редакторе VIM 😉

Источник

Copy the contents of a file into the clipboard without displaying its contents

How to copy the contents of a file in UNIX without displaying the file contents. I don’t want to cat or vi to see the contents.

I want to copy them to clipboard so that I can paste it back on my windows notepad.

I can’t copy the file from that server to another due to access restrictions.

3 Answers 3

If using X11 (the most common GUI on traditional Unix or Linux based systems), to copy the content of a file to the X11 CLIPBOARD selection without displaying it, you can use the xclip or xsel utility.

to store the content of file as the CLIPBOARD X11 selection.

To store the output of a command:

Note that it should be stored using an UTF-8 encoding or otherwise pasting won’t work properly. If the file is encoded using an another character set, you should convert to UTF-8 first, like:

for a file encoded in latin1/iso8859-1.

xsel doesn’t work with binary data (it doesn’t accept null bytes), but xclip does.

To store it as a CUT_BUFFER (those are still queried by some applications like xterm when nothing claims the CLIPBOARD or PRIMARY X selections and don’t need to have a process running to serve it like for selections), though you probably won’t want or need to use that nowadays:

(removes the trailing newline characters from file ).

GNU screen

GNU screen has the readbuf command to slurp the content of a file into its own copy-paste buffer (which you paste with ^A] ). So:

Apple OS/X

Though Apple OS/X can use X11. It doesn’t by default unless you run a X11 application. You would be able to use xclip or xsel there as OS/X should synchronise the X11 CLIPBOARD selection with OS/X pasteboard buffers, but that would be a bit of a waste to start the X11 server just for that.

On OS/X, you can use the pbcopy command to store arbitrary content into pasteboard buffers:

(the file’s character encoding is expected to be the locale’s one). To store the output of a command:

Shells

Most shells have their own copy-paste buffers. In emacs mode, cut and copy operations store the copied/cut text onto a stack which you yank/paste with Ctrl-Y , and cycle through with Alt+Y

zsh CUTBUFFER/killring

In zsh , the stack is stored in the $killring array and the top of the stack in the $CUTBUFFER variable though those variables are only available from Zsh Line Editor (zle) widgets and a few specialised widgets are the prefered way to manipulate those.

Because those are only available via the ZLE, doing it with commands is a bit convoluted:

The zle-line-init special widget is executed once at the start of each new command prompt. What that means is that the file will only be copied at the next prompt. For instance, if you do:

The file will only be copied after those 2 seconds.

Источник

How to copy file in clipboard buffer when running ssh on linux?

For example I am Using Mac and ssh’ed to Linux server(Ubuntu, no X-session) and need to transfer SSL certificate from one server to another (also Linux console, Ubuntu, no X-session), how would I copy certificate with clipboard, is it possible?

I know how to copy using cat and mouse 🙂 For example cert is not printable in console or too big

3 Answers 3

To copy a file from one server to another I would usually use scp . It is a program to copy files over ssh. You can either scp the file from the first Ubuntu to your Mac and then from your Mac to the second Ubuntu, or if there are no firewalls and such you can scp directly from the first Ubuntu to the second. The syntax is scp localpathsrc login@server:remotepathdst or scp login@server:remotepathsrc localpathdst (with the newest scp I think you can also use scp login1@server1:path1src login2@server2:path2dst, but you won’t have that on your Mac nor on Ubuntu 12.04). On Ubuntu you should have scp, it comes in the package openssh-client, but maybe you only have openssh-server installed. On Mac, I’m afraid I don’t know.

Читайте также:  Сервер доменных имен windows

Without installing anything at all you should also be able to do from a terminal on your Mac

but I don’t remember if that works when you have to type passwords.

X Toolkit

I think you just want some tools from the standard X Toolkit:
xclipboard ; xclip ; xcutsel ; xclip-copyfile ; xclip-cutfile ; xclip-pastefile ; etc..

I cannot seriously believe that you are using a Linux console. do you have a mouse? If so:

use the command cat myfile to show the whole file on your terminal. Make the terminal bigger if necessary to show the whole file. If it’s just a certificate it shouldn’t be a problem.

Place the mouse pointer at the beginning of the file shown in your terminal.

Hold down the left button

Move the mouse to the other end of the file so that it is all highlighted

Release the mouse button. The file’s contents should stay highlighted. This copies the highlighted text to the X clipboard (which is a different one than the one you use when you do Ctrl-C/Ctrl-V in some applications).

Access your other server.

Open a file editor (if you use vi put it in insert mode)

Press the mouse middle button to paste the contents.

If you’re not using a mouse, then you may not have X libraries installed. Use scp instead of the X clipboard.

This is supposing you are actually logged on a X session. Given the vagueness of your question you might be on a Windows PC and using putty to access the two linux servers. If so, use the right button to paste.

Источник

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:

Читайте также:  Linux mint update upgrade

(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:

Источник

How to copy the GNU Screen copy buffer to the clipboard? [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 5 months ago .

When using GNU Screen we can work with scrollback buffer also known as «copy mode» using the Ctrl+a+[ command.

In there we can copy text to the copy buffer by pressing space selecting the text and pressing space again.

Is there some way to copy this text from screen copy buffer to the X clipboard?

In my case I’m using Ubuntu 12.04 with gnome and Xorg.

9 Answers 9

You can use a CLI clipboard tool like xsel or pbpaste and the cat utility to grab contents from STDIN. The steps on Linux with xsel are as follows:

  1. Copy text from your screen session into GNU screen’s copy buffer.
  2. Run this command within screen: cat | xsel -b
  3. If xsel didn’t report any error, now dump screen’s copy buffer to STDIN: Ctrl+a+]
  4. Send an EOF to cat to terminate it: Ctrl+d

At this point, the contents of the screen copy buffer should be in your clipboard.

EDIT: As with all X programs, xsel needs to know how to contact your X server in order to access the clipboard. You should have your DISPLAY environment variable set appropriately.

This answer applies to OS X.

After copying the desired text into the GNU Screen paste buffer using copy mode, do the following:

  1. In any of your screen windows, type pbcopy .
  2. Then paste your text into the terminal using the GNU Screen paste command ( Ctrl-a ] unless you’ve changed your escape key).
  3. If the text does not end in a newline, press to insert one.
  4. Finally, press Ctrl-d to cause pbcopy to push the text to the system clipboard.

Then you can paste the text elsewhere in OS X as usual using Command-v or an equivalent menu option.

There is a simpler and less manual way to do this. In your screen .rc file, add the following line:

How to use the copy functionality:

  1. screen -c path/to/screen/config.rc
  2. Hit Ctrl+A then Esc to enter copy mode.
  3. Scroll up the text buffer and find the spot you want to leave your start marker for copying, then hit space.
  4. Scroll down and select the text you wish to copy. When you are done, hit space again.
  5. The text will now be in your clipboard.

EDIT: On Linux with no pbcopy but with clipit, you can use as below:

bindkey -m ‘ ‘ eval ‘stuff \040’ ‘writebuf’ ‘exec sh -c «/bin/cat /tmp/screen-exchange | /bin/clipit»‘

This answer works for only a scenario where your end target is to paste the copied buffer contents immediately.

The simplest way to do this is by splitting your screen into two regions. You can do this by hitting CTRL + a then | ‘This is not an i. It is the PIPE sign on your keyboard’

Hit CTRL + a then TAB to switch to the second region, CTRL + a then c to create a new session in the second region.

If you want to copy from nano and paste in terminal, open up the file in nano on the left region, hit CTRL + a then ESC , scroll to the start point of your copy location and hit SPACE , select the text by scrolling to the end point and hit SPACE again to mark copy.

Now, all you have to do is hit CTRL + a then TAB to switch to the region on your right and hit CTRL + a then ] .

Your text will be written out to the command line. Note that you can also check for hardcopy option if you want to write directly to file.

Источник

Оцените статью