I'd like to grep and open a file in just one terminal command.

Suppose I'm in this directory:

$ ls
1.txt   2.txt   3.txt   4.txt   5.txt

and I want to open 3.txt

I thought I could do ls | grep 3 | open

but it looks like open doesn't accept piped input. Is there any way to do this?


Try open $(ls | grep 3). Depending on your specific needs, you can also skip the grep part and use open $(ls *3*) (or even open *3*) directly.

| improve this answer | |
  • What is the difference between open $(ls *3*) and just open *3*? – David Anderson Feb 4 '16 at 11:17
  • None in this case, good point :-). I assume that the OP had more complex patterns in mind. – nohillside Feb 4 '16 at 12:27
  • 2
    Pro Tip: Always add a -- before the glob * when doing ls, rm, open and so on. And never create files named "-rf"... – bot47 Feb 4 '16 at 13:13
  • Parsing ls to produce file name arguments is a bad idea. You can get undesirable results if the directory contains file names with spaces that match the pattern/glob. – fd0 Feb 4 '16 at 16:48

Another option

find . -name "*3*" -exec open {} \;

Will run open on any file with 3 in it's name from the current directory down. The spaces and backslash matter in this case.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .