I just bumped into this issue, but echo
didn't work with my particular use case which was looping through an array and printing the contents. I just couldn't get the formatting right with echo
, so needed to keep the sed
. But as @pomsky rightly notes, it doesn't like empty files. Ugh.
Solution:
So for my particular use-case, I echo
'ed a blank space into the newly created file:
if [ ! -s file ]; then echo "" > file; fi
The test will not evaluate as true
because although the file is empty, it does not have a size greater than zero on a clean file created by touch
- thus my use of negation !
. A blank space will now be echoed on the first line.
When I subsequently execute:
sed -i "1i blah" file
Now my sed
will work on the "empty" file. I didn't actually print "blah", but looped through the contents of array ;-).
If you're in a similar situation where you can't just use echo
in lieu of sed
, I hope this saves you cycles solving the same problem that drove me bananas...
My test text
at the end of the file, unless it is an empty file (good catch @pomsky).