3

I am trying to use xsel clipboard to pipe search term to grep to search in folder full of txt files. Can anybody suggest a method to do it.

Ramaprakasha
  • 215
  • 1
  • 7

1 Answers1

3

With grep implementations that support of -r option for recursive grep:

grep -rFe "$(xsel -b -o)" /path/to/your/folder

For other grep implementations, use find to look up the files:

find /path/to/your/folder -type f -exec \
  grep -Fe "$(xsel -b -o)" /dev/null {} +

The /dev/null is to make sure at least 2 file names are passed to grep so grep always prints the name of the files the strings are found in.

Note that if the CLIPBOARD selection contains more than one line, each line will be searched separately. For instance, if the selection contains a<newline>b, it will report lines that contain a or b (or both).

To match on a<newline>b instead, you could use pcregrep with its multiline mode:

pcregrep -rM "\Q$(xsel -b -o | sed 's/\\E/&\\&\\Q/g'; printf '\\E')" /path/to/folder
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501