Solving the open command problem in MacOS Terminal / by Joseph Palumbo

I don't like to take my fingers off the keyboard when I'm working. Moving my hands to reach for the trackpad of a mouse is a waste of time in my opinion, so I'm always looking for ways to maximize the use and flexibility of my keyboard. 

In this pursuit, the open command in MacOS has become one of my favorite tools. It allows me to open either an application, a file, or a file with a specific application straight from the command line. 

However, one of the limitations of the open command is that I could not pipe files into it. For example, if I wanted to open the last 5 .csv files that I downloaded, I want to be able to type

$ ls -t *.csv | head -n5 | open

It wouldn't work. That is until now. 

The First Solution 

After some extensive Googling, I found this trick to open files that meet specific criteria. 

$ open $(ls -t *.csv| head -n5)

The command above lists only the last 5 *.csv files that were modified in the current directory and  opens them in their default application. In this case, Microsoft Excel. 

The Second Problem

This worked great until I came across a file name with a blank space in the name. The command interpreted that blank space as two separate files and returned an error like this: 

Could not find /Users/Palumbo/Documents/first_part_of_file_name
Could not find /Users/Palumbo/Documents/last_part_of_file_name

The Second (and Third) Solution

OK, so the open command was working the way I wanted it to as long as the file's names did not have a blank space in them. So what's the best way to make that change on a quick and/or automated basis. 

Hazel

The first thing I did was open up Hazel which is an app that will monitor Folders and perform actions on files if they meet criteria defined by the user. (If you're not using it, you definitely should be)

I export a lot of .csv files from a platform I use at work called ClientSuccess, and they always export using predictable file names: 

  1. ClientSuccess_Export.csv
  2. ClientSuccess_Export (1).csv
  3. ClientSuccess_Export (2).csv

and so on. 

I created a rule in Hazel to watch my Downloads folder for files that named ClientSuccess_Export followed by a blank space then followed with anything after that. When it finds such a file it executes a bash script to replace the blank spaces with an '_'. 

 How I set up my Hazel rule. 

How I set up my Hazel rule. 

That solves the problem with multiple exported files from ClientSuccess, but what about any other files that might have blank spaces on them. I could create a Hazel rule that would change any file with a space in the name, but that might be overkill for what I need. So I aliased the bash script from Hazel like this: 

alias btu="./Users/Palumbo/Code/btu.sh"

So any time I wanted to run a conversion on a file, I just need to type

$ btu file name with spaces.txt

and be returned with 

$ file_name_with_spaces.txt