wim*_*wim 7 command-line clipboard xclip
我想拦截粘贴事件并通过我的脚本运行任何文本。用例是这样的(假设我在某处有一个脚本,它接受标准输入上的文本并将“世界”变成“土豆”,写在标准输出上)。
在 1 和 2 之间不应该有手动步骤,即我想要在 paste 事件(或者可能是在 copy 事件上)一个钩子,以便自动处理文本。我没有任何恶意;它只是在从/向网络复制/粘贴时自动格式化一些源代码。
我的问题涉及选择缓冲区(鼠标中间剪贴板),但我想这个问题通常也适用于其他剪贴板文本。
您可以使用它clipnotify
来获取剪贴板更改通知,而无需轮询。从项目页面:
while clipnotify; do
[an event happened, do something with the selection]
done
Run Code Online (Sandbox Code Playgroud)
该工具只有几行使用 XFIXES 功能的 C 代码。
You can use the following Bash function. Copy it to your ~/.bashrc
and source it as . ~/.bashrc
from a terminal.
cngstr(){
echo `xclip -o` | sed -e "s#$1#$2#g" | xclip
}
Run Code Online (Sandbox Code Playgroud)
Run in terminal:
$ cngstr "string" "replacement"
Run Code Online (Sandbox Code Playgroud)Next when you paste using mouse middle click, the word(s) "string" in your selection will be replaced with "replacement".
Say your selection is "hello world!". Next you run in terminal,
cngstr world potato
Run Code Online (Sandbox Code Playgroud)
Use ""
for a string consisting of more than one word. Next when you paste using the mouse middle clip, "hello potato!" will appear. See the screenshots.
xclip -o
prints the selection to standard output which is being piped to sed
here.sed
is replacing the strings taking input from the user.xclip
which put it in the primary selection and becomes available for pasting by a mouse middle click.I think xclip
comes with the default Ubuntu distribution. Otherwise install it through apt-get
:
sudo apt-get install xclip
Run Code Online (Sandbox Code Playgroud)
Make the modified contents available to clipboard also
If you want the modified contents also be available to the clipboard so that Ctrl+V also works as well, add the following line in the above script.
$ cngstr "string" "replacement"
Run Code Online (Sandbox Code Playgroud)
The above line will pass the contents of the primary selection to the clipboard. The modified function will look like:
cngstr world potato
Run Code Online (Sandbox Code Playgroud)
A Bash function that can modify contents of the clipboard (i.e., copied using Ctrl+C or from the right click menu) and make the modified string available to the primary selection as well as to the clipboard.
sudo apt-get install xclip
Run Code Online (Sandbox Code Playgroud)
xclip -o
prints the contents of the primary selection by default. Use -selection c
to print the contents of the clipboard. See man xclip
for more.
You can combine these two functions in a script using a switch case,
echo `xclip -o` | xclip -selection c
Run Code Online (Sandbox Code Playgroud)
Usage
./script.sh [c|p] "string" "replacement"
Run Code Online (Sandbox Code Playgroud)
Use option c
for altering contents copied using the clipboard i.e., contents copied using Ctrl+C or from the right click menu.
使用选项p
更改使用主要选择复制的内容。