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.
Asked
Active
Viewed 154 times
3
Ramaprakasha
- 215
- 1
- 7
1 Answers
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
-
With `GNU grep`, option `-H` can be used instead of `/dev/null`... not sure about other versions... – Sundeep Apr 26 '17 at 11:44
-
1@Sundeep, yes that's a GNU extension. IOW, `grep` implementations that have `-H` also have `-r`. – Stéphane Chazelas Apr 26 '17 at 11:49