1

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?

1

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.

  • 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"... – Max Ried 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
1

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.

You must log in to answer this question.

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