Using Bash only
You can use Command Substitution (remove trailing newlines) with Here Strings (appends newline):
Command Substitution
Command substitution allows the output of a command to replace the command name. There are two
forms:
$(command)
or
`command`
Bash performs the expansion by executing command in a subshell environment and replacing the com-
mand substitution with the standard output of the command, with any trailing newlines deleted.
Embedded newlines are not deleted, but they may be removed during word splitting. The command sub-
stitution $(cat file) can be replaced by the equivalent but faster $(< file).
Here Strings
A variant of here documents, the format is:
[n]<<<word
The word undergoes brace expansion, tilde expansion, parameter and variable expansion, command sub-
stitution, arithmetic expansion, and quote removal. Pathname expansion and word splitting are not
performed. The result is supplied as a single string, with a newline appended, to the command on
its standard input (or file descriptor n if n is specified).
Here's how it works:
cat <<<"$(<inputfile)"
Output to file:
cat <<<"$(<inputfile)" >outputfile
If you need inputfile
and outputfile
to be the same file name, you have a couple options - use sponge
command, save to temporary variable with more command substitution, or save to temporary file.
Using Sed
Others have suggested using
sed '$a\' inputfile
which appends nothing to the last line. This is fine, but I think
sed '$q' inputfile
is a bit clearer, because it quits on the last line. Or you can do
sed -n 'p'
which uses -n
to suppress output, but prints it back out with p
.
In any of these cases, sed
will fix up the line and add a newline, at least for GNU and BSD sed. However, I'm not sure if this functionality is defined by POSIX. A version of sed
might just skip your line without a newline since a line is defined as
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.
tee -a
should be used. See How to add newline character at the end of many files – Mime