linux - 使用 sed 删除最后一个换行符

标签 linux unix sed file-manipulation end-of-line

<分区>

如何从文件中删除最后一个 \n。该文件有一个最后一个空行,用于在最后一个文本行中换行。我正在使用这个命令:

sed '/^\s*$/d'

但是那个空白行并没有被删除。

最佳答案

为什么是sed打印换行符?

当您阅读 sed POSIX standard , 然后它说:

Whenever the pattern space is written to standard output or a named file, sed shall immediately follow it with a <newline>.

可以在 this answer 中找到更多详细信息.

删除最后一个 <newline> :

  • truncate : 如果你只想从一个文件中删除一个字符,你可以这样做:

    truncate -s -1 <file>
    

    这会使文件缩短一个字节,即删除最后一个字符。

    From man resize: -s, --size=SIZE set or adjust the file size by SIZE bytes

    SIZE may also be prefixed by one of the following modifying characters: '+' extend by, '-' reduce by, '<' at most, '>' at least, '/' round down to multiple of, '%' round up to multiple of.

  • 其他答案可以在 How can I delete a newline if it is the last character in a file? 中找到

关于linux - 使用 sed 删除最后一个换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50559170/

相关文章:

sed - 使用 sed 获取文本文件的第 x、y 和 z 行

sed - 从 sed 和 awk 打印详细进度

linux - Python 不接受 crontab

linux - 如何调试导致 "emacs24.4 --daemon"不返回shell的init文件?

python - 如何在 Python 中将时间列表转换为 Unix 纪元时间?

macos - 在 OS X 中使用 find 来识别正确的权限

java - 没有 mod_rewrite 的 Apache URL 重写

linux - 如何根据文件移动文件(文件名和文件中的位置)

作为 Unix 服务运行的 Java

command-line - 如何在 sed 中匹配多个地址?