Sunday, May 19, 2024

Using TextEditor from the Command Line

A lot of people find the ASCII based command-line text editors (like Vim) a pain to work with. Here’s a few suggestions on how to easily invoke TextEditor (or any other GUI based editor you prefer) from the command line in Terminal.

To open a file within Terminal using TextEditor, use this command:

open -a TextEditor /path/file.txt

The -a switch allows you to specify any application you like, and it will call up any existing instance of that app. In this case, if you have TextEditor already open, the file will open in a new window on that instance of TextEditor. You can also call up any other text editor you prefer, such as BBEdit or Coda for example. Also, you won’t need to put in the /path if you’re already in the directory where the file exists.

You can also use the -t switch to open the file in whatever the default application is for that filetype.

Then there’s the -e which will open the file automatically with TextEditor, so there is no need to specify TextEditor yourself. It would look like this:

open -e /path/file.txt

If the file is locked, you may need admin rights. Then it is better to use the -e switch, because if you specify TextEditor directly, the file may still be un-editable once opened. Just use this command (but only if you need to).

sudo open -e /path/lockedfile.txt

Making it easier to remember

You can make this even easier, by eliminating the need to remember the original command I gave above. We’ll do this by setting up an alias in your bash_profile.

open -e ~/.bash_profile

If you don’t have a bash_profile (you’ll get an error telling you so), just use the touch command to create one (Note: the touch command is designed to update the modified data on a file, but if the file does not exist, it will create it):

touch ~/.bash_profile

Then run the open command given above.

Now, add these two lines:

alias textedit='open -a TextEdit’
alias sutextedit=‘sudo open -e’

You can put something else in place of the alias “textedit” if you like, such as “tedit”. You’ll need to reload the bash_profile if you want this to function immediately. Use this command:

source ~/.bash_profile

or (to save a few keystrokes)

. ~/.bash_profile

Now when you want to edit a file from Terminal just type in:

textedit /path/filename.txt

This tip can be used for other commands you find it hard to remember.


Recent Articles


Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox