1

I would like to somehow create links to files within the terminal from search results found when searching files. Same way you would click a hyperlink within the terminal, but in this case it would be a file and not an URL. Is this possible?

Below is the command in which I am working with.

grep -rnw "$2" -e "$1"

... and here is a screenshot when searching my logs for term "filezilla"

enter image description here

I would like to be able to click on the purple text which are exact file locations, the same way I would open a hyperlink within the terminal.

I tried this command below, but all this does is automatically open every search result found with the preferred program, in this case the program being mousepad.

grep -rnw "$2" -e "$1" | xargs mousepad

1 Answer 1

1

Recent terminal emulators do handle hyperlinking to a limited extent. Provided that it 'knows' which programme to use to open a document then you just need to echo the file name to stdout in the terminal window with the correct protocol in front. Since we are dealing with local files then this means changing

/path/to/file/this.doc

to

file:///path/to/file/this.doc

Just like a hyperlink but without a domain name. Provided your shell knows how to open a file type then it will do so.

for i in $(ls); do echo "file://$(pwd)/$i"; done

ctrl+click

EDIT

To bring @tripleee excellent improvement out from the comments and into the answers...

printf "file://$(pwd)/%s\n" *

END EDIT

This will not work for files with spaces in the file names because the expansion of $(ls) produces a list of file names separated by spaces. A space within a file name will make the shell think it is actually two file names separated by a space.

my file.pdf

becomes

my
file.pdf

If you have spaces in your filenames then try this until you find a more elegant solution since I just hacked it in anticipation of the next question...... ;-)

for f in $(find . -type f -maxdepth 1 -iname "*" | sed 's/ /%20/g'); do echo "file://$(pwd)/${f#*/}"; done

Just use find in the normal way to return the files you want.

4
  • I am confused, where does the search term go?
    – Anonymous
    Feb 3, 2019 at 18:51
  • Can you update your question so that it helps someone in which you are not assuming knows bash-scripting as well as you? Thanks.
    – Anonymous
    Feb 3, 2019 at 18:52
  • You can easily avoid the useless use of ls; printf "file://$(pwd)/%s\n" *
    – tripleee
    Feb 4, 2019 at 10:52
  • @tripleee I count myself educated on this use of ls thats a nice little nugget of knowledge.
    – bu5hman
    Feb 4, 2019 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.