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

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.

Читайте также:  Windows server 2019 core настройка сетевого адаптера

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

Читайте также:  Оптимизация windows 10 домашняя для одного языка

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.

Источник

How can I copy the output of a command directly into my clipboard?

How can I pipe the output of a command into my clipboard and paste it back when using a terminal? For instance:

22 Answers 22

I always wanted to do this and found a nice and easy way of doing it. I wrote down the complete procedure just in case anyone else needs it.

First install a 16 kB program called xclip :

You can then pipe the output into xclip to be copied into the clipboard:

To paste the text you just copied, you shall use:

To simplify life, you can set up an alias in your .bashrc file as I did:

To see how useful this is, imagine I want to open my current path in a new terminal window (there may be other ways of doing it like Ctrl + T on some systems, but this is just for illustration purposes):

Notice the ` ` around v . This executes v as a command first and then substitutes it in-place for cd to use.

Only copy the content to the X clipboard

If you want to paste somewhere else other than a X application, try this one:

On OS X, use pbcopy ; pbpaste goes in the opposite direction.

I’ve created a tool for Linux/OSX/Cygwin that is similar to some of these others but slightly unique. I call it cb and it can be found in this github gist.

In that gist I demonstrate how to do copy and paste via commandline using Linux, macOS, and Cygwin.

Linux

macOS

Cygwin

Note: I originally just intended to mention this in my comment to Bob Enohp’s answer. But then I realized that I should add a README to my gist. Since the gist editor doesn’t offer a Markdown preview I used the answer box here and after copy/pasting it to my gist thought, «I might as well submit the answer.»

A leak-proof tee to the clipboard

This script is modeled after tee (see man tee ).

It’s like your normal copy and paste commands, but unified and able to sense when you want it to be chainable

Examples

Paste

Chaining

Copy via file redirect

(chronologically it made sense to demo this at the end)

I wrote this little script that takes the guess work out of the copy/paste commands.

The Linux version of the script relies on xclip being already installed in your system. The script is called clipboard.

The OS X version of the script relies on pbcopy and pbpaste which are preinstalled on all Macs.

Using the script is very simple since you simply pipe in or out of clipboard as shown in these two examples.

/.scripts/clipboard * Make it executable chmod +x

/.scripts/clipboard for bash: * add export PATH=$PATH:

/.scripts to the end of

/.bashrc for fish: * add set PATH

/.scripts $PATH to

/.config/fish/fish.config If any of the files or folders don’t already exist just create them.

Add this to to your

Now clipp pastes and cclip copies — but you can also do fancier stuff:

↑ indents your clipboard; good for sites without stack overflow’s < >button

You can add it by running this:

Linux, macOS, Windows (WSL/CYGWIN)

Each of those systems use its own tool to incorporate the clipboard functionality into the command line interface (CLI). This means, when using for example the Ubuntu CLI on Windows Subsystem for Linux (WSL) the usual xclip solution won’t work. The same holds true for macOS.

The following table provides an overview for the copy/paste tools needed on the different systems:

OS Copy Paste
WSL clip.exe powershell.exe Get-Clipboard
CYGWIN > /dev/clipboard cat /dev/clipboard
macOS pbcopy pbpaste
Linux xclip -sel clip xclip -sel clip -o

Unified .bashrc solution

Just put the following code into your

/.bashrc to enable the usage of copy and paste on all systems. The solution works on «normal» Linux systems (i.e. Ubuntu, Debian) as well as on WSL and macOS:

Usage on ALL systems

For mac this is an example way to copy (into clipboard) paste (from clipboard) using command line

Copy the result of pwd command to clipboard as

Use the content in the clipboard as

Without using external tools, if you are connecting to the server view SSH, this is a relatively easy command:

From a Windows 7+ command prompt:

This will put the content of the remote file to your local clipboard.

(The command requires running Pageant for the key, or it will ask you for a password.)

I am using Parcellite and xsel to copy last commit message from git to my clipboard manager (for some reason xclip does not work):

I usually run this command when I have to copy my ssh-key :

cmd+v or ctrl+v anywhere else.

I made a small tool providing similar functionality, without using xclip or xsel. stdout is copied to a clipboard and can be pasted again in the terminal. See:

Note, that this tool does not need an X-session. The clipboard can just be used within the terminal and has not to be pasted by Ctrl+V or middle-mouse-click into other X-windows.

For those using bash installed on their windows system (known as Windows Subsystem for Linux (WSL)), attempting xclip will give an error:

Instead, recall that linux subsystem has access to windows executables. It’s possible to use clip.exe like

which allows you to use the paste command (ctrl-v).

In Linux with xclip installed:

I come from a stripped down KDE background and do not have access to xclip , xsel or the other fancy stuff. I have a TCSH Konsole to make matters worse.

Requisites: qdbus klipper xargs bash

Create a bash executable foo.sh .

Note: This needs to be bash as TCSH does not support multi-line arguments.

Followed by a TCSH alias in the .cshrc .

Explanation:

xargs -0 pipes stdin into a single argument. This argument is passed to the bash executable which sends a «copy to clipboard» request to klipper using qdbus . The pipe to /dev/null is to not print the newline character returned by qdbus to the console.

This copies the contents of the current folder into the clipboard.

Note: Only works as a pipe. Use the bash executable directly if you need to copy an argument.

on Wayland xcopy doesn’t seem to work, use wl-clipboard instead. e.g. on fedora

Based on previous posts, I ended up with the following light-weigh alias solution that can be added to .bashrc :

2021 Answer

If you were searching for an answer to the question, «How do I copy the output of one command into my clipboard to use for my next command?» like I was, then this solution works great as a Mac user.

In my example, I wanted to simply copy the output of $ which postgres so I could simply paste it in my next command.

I solved this by piping my first command $ which postgres with $ pbcopy .

Then I could simply command + V which produced my desired result:

macOS:

WSL / GNU/Linux (requires the xclip package):

Git Bash on Windows:

Here’s great solution for Arch Linux users. Install xsel with pacman, like:

Create alias in

/.bashrc file, like:

reload your terminal with source:

use it like mentions above:

fyi, good practice stroing all of the aliases in

/.aliases and call it in .bashrc file

Just to cover an edge case:) and because the question title asks (at least now) how to copy the output of a command directly to clipboard.

Often times I find it useful to copy the output of the command after it was already executed and I don’t want to or can’t execute the command again.

For this scenario, we can either use gdm or a similar mouse utility and select using the mouse. apt-get install gdm and then either the right click or the Cntrl+Shift+c and Cntrl+Shift+v combinations for copy and paste in the terminal

Or, which is the preferred method for me (as the mouse cannot select properly inside one pane when you have multiple panes side by side and you need to select more than one line), using tmux we can copy into the tmux buffer using the standard [ , space , move to select , enter or you can select a block of code. Also this is particularly useful when you are inside one of the lanes of the cli multiplexer like tmux AND you need to select a bunch of text, but not the line numbers (my vim setup renders line numbers)

After this you can use the command:

You can of course alias it to something you like or bind directly in the tmux configuration file

This is just to give you a conceptual answer to cover this edge case when it’s not possible to execute the command again. If you need more specific code examples, let me know

Источник

Читайте также:  Mac os вырезать вставить файл
Оцените статью