Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想在文件末尾追加一个新行,但我正在使用的一些文件可能不包含换行符作为它们的最后一个字符,这意味着我要追加到同一行。
有没有一种简单的方法来检查换行符并进行相应调整?
echo "some line of text" >> aFile.txt
您可以使用:
x=$(tail -c 1 aFile.txt) if [ "$x" != "" ] then echo >> aFile.txt fi echo "some line of text" >> aFile.txt
操作员从嵌入在其中的命令的输出中$(...)删除尾随换行符,并且该tail -c 1命令打印文件的最后一个字符。如果最后一个字符不是换行符,则字符串"$x"不会为空,因此在添加新的文本行之前向文件添加换行符。
$(...)
tail -c 1
"$x"