GiselleSerate / myaliases

Useful shell aliases and functions.
6 stars 1 forks source link

the prepend command #87

Closed aryarm closed 5 years ago

aryarm commented 5 years ago

Note: Make sure you decide whether to merge #88 before you merge this one.

Ever since I realized that I could portably prepend text to a file using the syntax described in issue #72, I've been using the idiom quite often. Unfortunately, it's quite lengthy and sometimes hard to remember, so I decided to whip up a quick function alias for it.

Motivation

Prepending text to a file can be a difficult task. The classic idiom is to use GNU sed's in-place editing feature -i. However, sed -i (as well as most other methods) use a temporary file in the background. In addition, not every user will have GNU sed installed, so this strategy isn't portable.

The prepend command is a portable way to prepend text to a file without creating a temporary file. This is usually faster because it allows one to bypass unnecessary file IO operations. Text can be specified either from stdin or as arguments to the command. In addition, prepend is flexible enough to work with almost any type of file, including named pipes. Note, however, that prepend is not recommended for large files.

Usage

prepend <file> <text>
cmd | prepend <file>
aryarm commented 5 years ago

An alternative implementation

(adapted from https://stackoverflow.com/a/14077361)

cmd | { echo '0a' && cat && echo -e ".\nw"; } | ed file 2>/dev/null

I think this works because ed creates an in-memory copy of the file before it writes it. And this feature of ed seems to be POSIX so I think it's technically portable. And it might even be better than my current solution in cases where prepend might be killed while it is executing (since that might usually corrupt the file)? Update: ed actually keeps a temporary copy of the file somewhere while it is executing, so maybe it's not better than the current implementation after all

GiselleSerate commented 5 years ago

I'm gonna say we should probably catch usage errors (e.g. no arguments) for prepend.

aryarm commented 5 years ago

good point! see 63d2236

GiselleSerate commented 5 years ago

Wait, it looks like you tried to make it error out or something--when I try to run prepend on its own with no arguments I get:

touch: cannot touch '': No such file or directory 

And then it hangs, presumably waiting for input, until I Ctrl-C out.

aryarm commented 5 years ago

That was the old behavior. Are you sure you're working with the new code? You can do type prepend to check.

GiselleSerate commented 5 years ago

Oh boy--maybe I merged badly. Lemme look. EDIT: Nope, forgot to source. My bad.