Linux copy text to clipboard

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.

This really doesn’t look like a duplicate to me. One answer is about general copy paste generally, and this one is about copy a file specific subject

How about a when a complete non-GUI Ubuntu is being used through ssh from macOS Terminal app or analogue?

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

sudo apt-get install xclip 

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

cat ./myfile.txt|xclip -i -selection clipboard 

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:

find $ -name "*.pdf"| xclip -i -selection clipboard -t text/uri-list 

(at least this works for me in KDE). Now you can wrap into a small script which you can call, say, cb :

#!/bin/sh xclip -i -selection clipboard -t text/uri-list 

then you put it in ~/bin , set executable bit on it and use it like this:

Источник

Copying text from a terminal

Most mature terminal emulators permit users to copy or save their contents.

Читайте также:  Running chrome on linux

General approach

In graphical terminal emulators, contents are typically selectable by mouse, and can then be copied using the context menu, Edit menu or a key combination such as Ctrl+Shift+c .

Terminals without CLIPBOARD selection

Xorg

Some emulators do not support the CLIPBOARD selection natively, and copy data to the PRIMARY selection. For them xclip may be used:

$ xclip -o | xclip -selection clipboard -i

The above command reads data from the PRIMARY selection and writes it to CLIPBOARD selection.

Other clipboard managers such as autocutsel provide automatic synchronization between selection buffers.

Wayland

Utilities like wl-clipboard and clipboard AUR can copy data to the Wayland clipboard:

Intercepting commands output

Use tee to intercept the output of a command.

$ command 2>&1 | tee output-file

After the command is executed, output-file will contain its output, while having displayed the output at the same time.

Accessing Linux terminal backlog

The backlog of a native terminal named /dev/ttyN may be accessed via /dev/vcsN . Hence, if one is working in /dev/tty1 , the following snippet will let store the backlog in a file output-file :

Comparison of common emulators

The factual accuracy of this article or section is disputed.

Unless the «Key combination» column states otherwise, the key combination is Ctrl+Shift+c .

Emulator Select to PRIMARY CLIPBOARD
Key combination Context menu Window menu Select
Alacritty Yes Yes No No No
aterm AUR Yes No No No No
eterm AUR Yes No No No No
germinal AUR Yes Yes Yes No No
Guake Yes Yes Yes No No
Konsole Yes Yes Yes Yes Optional
lilyterm-git AUR Yes Yes Ctrl+Delete Yes No No
lxterminal Yes Yes Yes Yes No
mate-terminal Yes Yes Yes Yes No
mlterm AUR Yes Yes No No Yes
pantheon-terminal Yes Yes Yes No No
PuTTY Yes No No No No
qterminal Yes Yes Yes Yes No
roxterm AUR Yes Yes Yes Yes No
rxvt AUR Yes No No No No
sakura AUR Yes Yes Yes Yes No
st Yes Yes No No No
Terminator Yes Yes Yes No No
terminology Yes Yes Yes No No
Termite Yes Yes No No No
Tilda Yes Yes Yes No No
urxvt Yes Yes Ctrl+Alt+c No No Optional
xfce4-terminal Yes Yes Yes Yes No
xterm Yes Optional[1] No No Yes
Yakuake Yes Yes Yes No Optional

Special cases

putty

The xclip approach works for putty: one just has to remember that the xclip invocation should be done on the local computer (in another terminal), not on the remote machine to which putty is connected.

urxvt

Selecting text to CLIPBOARD requires the selection-to-clipboard perl extension. See rxvt-unicode#Cut and paste for details.

xterm

Access to the CLIPBOARD selection in xterm requires additional steps.

mlterm

In addition to Ctrl+Shift+c , you can use Ctrl+Insert if you do not want to kill processes accidentally.

Источник

Работа с буфером обмена в Linux: теория и практика

Copy and Paste

Исторически сложилось так, что в X Window System (X11, — оконная система для Linux, UNIX) существует два буфера обмена.

Читайте также:  Linux kernel version header file

Один из них (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.

Скрипты

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

Update 3: Добавление пункта «копировать полный путь текущего файла» в меню Midnight Commander (Добавить в файл ~/.mc/menu):

_________
Текст подготовлен в редакторе 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.

if your file is huge the clipboard will fail anyway. When the access restrictions say, that you cannot read the file, you are lost of course. If you cannot copy the file because you can’t write the file you must ask yourself, if there is another destination you can write to.

Читайте также:  Astra linux разграничение прав доступа

You could, perhaps, edit the file on the system itself. You then wouldn’t need to copy the contents anywhere.

I just asked a related question since I can’t get xclip working when logging into Ubuntu from Git Bash on Windows: stackoverflow.com/q/60117294/470749

4 Answers 4

X11

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:

mycommand | xclip -sel c mycommand | xsel -b 

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:

xprop -root -format CUT_BUFFER0 8s -set CUT_BUFFER0 "$(cat file)" 

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

zmodload zsh/mapfile zle-line-init() < if [ -n "$FILE_TO_COPY" ]; then zle copy-region-as-kill $mapfile[$FILE_TO_COPY] unset FILE_TO_COPY fi >zle -N zle-line-init file-copy() FILE_TO_COPY=$1:A 

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.

Источник

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