Quote:
Originally Posted by chrism01
Well, possibly
Code:
# instead of
... echo -e '\nfinishing line' ...
# you can just do
... echo "finishing line" ...
ie you'll get a newline anyway that way, unless you actually wanted a blank line inserted as well?
|
Actually both versions suffer from the same problem.
echo, on its own, only inserts a newline
after the string, not before it.
So if the file you're modifying does not have a final newline, then the first command above will supply it before inserting the text. But if it does have a newline already, then you'll end up with an extra blank line.
The second command does the opposite, of course. It will come out properly if there's already a newline, but if not then the new string will be concatenated with the final line of text.
To safely avoid this problem you should ensure that any trailing newlines are removed from the text before the operation, and then supply your own.
Here's one way, using
command substitution and
printf.
Code:
printf '%s\n%s\n' "$(<input-file.ext)" "finishing line" > newfile
One of the side-effects of
$(..) is that
it removes trailing newlines from the substituted text if it finds one. And bash lets you use
< inside of them to redirect the contents of a file directly (in other shells you can use
cat). Finally, quoting the whole thing means
printf sees the entire contents of the file (minus trailing newlines) as a single input argument.
I probably wouldn't use it if the file is exceptionally big though, as the whole thing is, I believe, temporarily copied to shell memory. Use the previously supplied
sed or
awk commands in that case.