As you may know, the alias
alias -g v='"$(xclip -selection c -o)"'
means that, when you invoke v
, the shell tries to execute a command named as the content of the clipboard. This is what happens in your first code snippet. However, invoking v
and observing its effects is misleading because the intended use for this global alias is to be an argument to other commands.
Your sed
-based solution will work if you properly use command substitution ($(...)
) and quoting:
alias -g v='$(xclip -selection clipboard -o | sed '"'"'s|^file://||'"'"')'
Here, xclip
pipes the content of the clipboard to sed
, which removes the file://
part at its beginning (the pattern is anchored, note the ^
). Avoiding /
as the s
command separator in the sed
script makes it more readable and removes the need to escape /
in the pattern.
The command substitution means that the output of the pipeline is substituted where v
is invoked.
You can then use it as:
cp -- v /path/to/destination
Beware that this will make it harder to act upon a file named v
in the current working directory, because the literal v
will be always substituted. As a workaround, you will be able to use the relative path ./v
.
(Also, consider that some programs accept non prefixed single-letter options, e.g. the perfectly legal (but non POSIX) ps v
. Single-letter global aliases are just unsafe).
And, last but not least, such a global alias won't work with files whose name contains space characters, because they will be split by the shell after the alias is substituted.
Alternatively, you may avoid a global alias and define:
alias v="xclip -selection clipboard -o | sed 's|^file://||'"
which can be used as:
cp -- "$(v)" /path/to/destination
This will also work with file names with space characters.
Note, however, that:
- Leveraging the substitution capabilities of the shell, as explained in thrig's answer, would be more efficient.
File names displayed by Dolphin and copied to the clipboard are encoded, and thus not suitable for being consumed by the shell as long as they include uncommon characters. For instance:
touch $'file with a\nnewline'
# Copied in Dolphin
% echo "$(v)"
file with a%0Anewline
% cat "$(v)"
cat: '/path/to/file with a%0Anewline': No such file or directory
ls
on termianl, it will show a single quote at beginnig and ending, like'abc wasd'
. And now after I copy'abc wasd'
to clipboard, how to make it work? I changed your answer to alias -g v='${"$(xclip -selection c -o)"//"#file://}' following https://unix.stackexchange.com/a/104887/232089. But, saddly it not worked. – roachsinai Feb 18 '19 at 02:34ls
in zsh which will surrounded by single quote all works. – roachsinai Feb 18 '19 at 02:41${${(Q)"$(xclip -selection c -o)"}#file://}
to remove one level of quoting – thrig Feb 18 '19 at 03:04sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
that I want to remove both leading and trailing spaces? – roachsinai Feb 18 '19 at 03:56