I want to create a text file and open it in a text editor with a single command.
I know touch file.txt
creates a file and open file.txt
opens the file, but is there a way to do this with a single command?
You could use touch myfile.txt; open myfile.txt
. If this is something you'll be doing frequently, you could create an alias for it.
alias touch_open='touch myfile.txt; open myfile.txt'
would work to create the Alias. Alternatively, could write a small function that would take in a parameter, ie. function touch_open { touch "$@"; open "$@"; }
and then run that as touch_open myfile.txt
Commented
Apr 4, 2013 at 14:39
If you are looking for some logic for this, ie. create a file and open if possible you could use something like this:
touch testFile && vi testFile
Here testFile is created with touch. The &&
part says if the creation was successful then open it with vi.
Also, you could just create a new file with something like vi, while opening it at the same time (this assumes you save the file after editing it).
vi testFile
That entirely depends on your text editor. Most will allow you to simply open a non-existent file, and assume you want it created on save.
You could also use a function if that is somehow not possible for you:
cropen() {
if ! [ "$1" ]; then
echo "need a file!" >&2
return 1
fi
: > "$1" && open "$1"
}
You can call it as cropen file
.
Use vim. Just type
vim newfile.txt
For vim you need to know the hot-keys.
i - Insert text in the file
esc - return to the command-input-mode
:w - Write (save)
:q - Quit (exit)
or (Easier to use Nano
):
nano newfile.txt
If you want a GUI type: (Works for ubuntu and other distros)
gedit newfile.txt
Like everyone is telling you, this depends on your editor. And if you don't like the way your editor handles this, that can probably be configured, as well.
With Emacs, emacs new_file.txt
(for a nonexistent new_file.txt
in the current directory) will bring up Emacs and display a buffer that refers to a new_file.txt
. However, until you save, there will be no such file. If you don't do anything and quit, no file will have been created.
While this is certainly one way, I think an even better way is to always have an instance of Emacs running. So, whenever you feel the need for a new file, go to Emacs, hit C-x C-f
(or M-x find-file RET
), then write the path to the nonexistent file, and you're at the same point as after the CLI command (above, in the second paragraph).
ed
,nano
,vi
,vim
,emacs
,teco
,LibreOffice
, ...) all regard a non-existent file as empty, and create the file upon exit (or when one writes the buffer). If your editor doesn't do that, it may be a bug.open(1)
man page, nor is it recognized as a command in Linux.