- Linux — copy/cut file into clipboard
- 3 Answers 3
- Работа с буфером обмена в 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
- Copy the contents of a file into the clipboard without displaying its contents
- 3 Answers 3
- GNU screen
- Apple OS/X
- Shells
- zsh CUTBUFFER/killring
- What is the command line equivalent of copying a file to clipboard?
- 4 Answers 4
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:
Источник
Работа с буфером обмена в 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.
Источник
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.
Источник
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:
Источник