1

I use grep to find unique (marker) text among a large number of files.

grep MarkerText -r -C 30 -h ~/helpfiles/*

Is it possible to feed a highlighted text as input to my grep command so that the highlighted text replaces MarkerText in this command? I am hoping to avoid having to copy and paste all the time.

1
  • Hint: highlight what you want and then use Shift+Insert. That should work on X11, not sure if Wayland has the same concept of Selections Aug 3, 2019 at 8:31

2 Answers 2

1

Yes, sure - there is PRIMARY selection in X11.

PRIMARY selection, is used when the user selects some data. X Window: Clipboard

You can use either xsel or xclip cli tools:

TL;DR

  1. Select some text

2a. grep "$(xsel)" -r -C 30 -h ~/helpfiles/*

OR

2b. grep "$(xclip -o)" -r -C 30 -h ~/helpfiles/*

Precondition

  • xsel or xclip package installed: apt get install xsel or apt get install xclip

  • X server is running (i.e. you use X server, not text-mode without X server): xset q > /dev/null && echo "X is running" || echo "start X server"

Explanation

Both xsel and xclip are clipboard management tools. Commands xsel and xclip -o print to STDOUT contents of PRIMARY selection. More info you can find here: 'xclip' vs. 'xsel'

Use double quotes around $(). This allows to highlight more than 1 word.

2
  • It worked! Thanks Yasen. I can now use this as some kind of a one-way hyperlink in pure text files. BTW is there a better way of creating such links in simple text files? For example something like TAGS in vim. Thanks again
    – user587469
    Aug 3, 2019 at 9:10
  • Some terminals can handle hyperlinlks and open $BROWSER. But I can't imagine a common way to use plain text as hypertext. Markdown maybe?
    – Yasen
    Aug 3, 2019 at 9:19
1

If you can install xclip package, try:

grep `xclip -o` -r -C 30 -h ~/helpfiles/*

"xclip -o" in above command will get replaced with whatever's on your clipboard.

You must log in to answer this question.