Как скопировать содержимое файла в буфер обмена linux
Перейти к содержимому

Как скопировать содержимое файла в буфер обмена linux

  • автор:

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.

Sergiy Kolodyazhnyy's user avatar

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 :

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.

Stéphane Chazelas's user avatar

4 Answers 4

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:

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:

25 Answers 25

One way of doing it follows:

Install xclip , such as:

sudo apt-get install xclip

Pipe the output into xclip to be copied into the clipboard:

cat file | xclip

Paste the text you just copied into a X application:

To paste somewhere else other than an X application, such as a text area of a web page in a browser window, use:

Consider creating an alias:

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

Benjamin Loison's user avatar

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." If you would like to discuss functionality/bugs it would probably be best to do that in the comments for the gist on github.

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.

Peter Mortensen's user avatar

/.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.

Native Solution with .bashrc Script

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

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:

Peter Mortensen's user avatar

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 by your machine’s shortcut for paste or in a command as in below

mcvkr's user avatar

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.)

Peter Mortensen's user avatar

d.raev's user avatar

macOS:

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

Git Bash on Windows:

dgor's user avatar

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

Tunaki's user avatar

Michal Przybylowicz's user avatar

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

cmd+v or ctrl+v anywhere else.

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).

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

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.

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.

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:

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

Как в терминале Linux копировать любой текст в буфер обмена

Xclip — утилита для работы с буфером обмена из консоли.

Установка в Ubuntu:

Данной утилитой можно скопировать любой вывод команды или текст какого-либо файла, чтобы скопировать туда, куда нам нужно. Также сама утилита позволяет вставлять из буфера обмена в консоль.

Использования утилиты на примере SSH pub ключа

Допустим, есть у нас публичный ключ ssh с названием id_rsa.pub, который мы хотим скопировать и вставить в систему для доступа к ней без ввода пароля:

Как в терминале Linux копировать любой текст в буфер обмена

Не совсем удобно копировать данный текст в терминале, можно ошибиться в пробелах и тд. Поэтому, давайте воспользуемся xclip.

Чтобы скопировать в буфер обмена, перенаправляем вывод любой команды в xlip :

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *