仅使用 Bash
您可以将命令替换(删除尾随换行符)与 Here Strings(附加换行符)一起使用:
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).
以下是它的工作原理:
cat <<<"$(<inputfile)"
输出到文件:
cat <<<"$(<inputfile)" >outputfile
如果您需要inputfile
和outputfile
要使用相同的文件名,您有几个选项 - 使用sponge
命令,使用更多命令替换保存到临时变量,或保存到临时文件。
使用 Sed
其他人建议使用
sed '$a\' inputfile
最后一行没有附加任何内容。这很好,但我认为
sed '$q' inputfile
更清楚一点,因为它在最后一行退出。或者你可以做
sed -n 'p'
它用于-n
抑制输出,但使用p
.
在任何这些情况下,sed
将修复行并添加换行符,至少对于 GNU 和 BSD sed。但是,我不确定此功能是否由 POSIX 定义。的一个版本sed
可能只是跳过你的行而没有换行,因为一行被定义为
零个或多个非字符加上一个终止字符的序列。