假设我有一些任意的多行文本文件:

sometext
moretext
lastline

如何仅删除文件的最后一个字符(e,而不是换行符或null),而不使文本文件无效?

推荐答案

更简单的方法(outputs to stdout,不更新输入文件):

sed '$ s/.$//' somefile
  • $是一个Sed地址,它只与最后一个输入行匹配,因此导致以下函数调用(s/.$//)只在最后一行上执行.

  • s/.$// replaces the last character on the (in this case last) line with an empty string; i.e., effectively removes the last char. (before the newline) on the line.
    . matches any character on the line, and following it with $ anchors the match to the end of the line; note how the use of $ in this regular expression is conceptually related, but technically distinct from the previous use of $ as a Sed address.

  • 使用stdin输入的示例(假定为Bash、Ksh或Zsh):

      $ sed '$ s/.$//' <<< $'line one\nline two'
      line one
      line tw
    

update the input file(如果输入文件是符号链接,则不要使用):

sed -i '$ s/.$//' somefile

Note:

  • 在macOS上,你必须使用-i ''而不是-i;有关-i的trap 概述,请参见this answer的下半部分.
  • 如果您需要处理非常大的输入文件和/或性能/磁盘使用率是一个问题and您使用的是GNU实用程序(Linux),请参阅ImHere's helpful answer.

Linux相关问答推荐

我想强调某些条件是否与Linux中的全部输出匹配

为什么硬编码的阿拉伯字母与Unicode代码点不具有相同的值

使用信号处理程序实现Hibernate 功能

使用awk命令将以:分隔的两个文件合并的方法

如何过滤 Bash 的正则表达式(Linux)中的所有值,除了一个?

X86 程序集 - struct 点 - 存储/返回不正确?

bind(): "无法分配请求的地址"

更改 awk 中的上一个重复行

如何在 AWS Linux 服务器上实现虚拟主机?

如何计算制表符分隔的文本文件中字段的唯一值的数量?

具体来说,fork() 如何处理 Linux 中 malloc() 动态分配的内存?

Linux 非阻塞 fifo(按需日志(log)记录)

如何在 linux ElementaryOS 中修复 Genymotion,但未找到错误CXXABI_1.3.8

在 bash 中检测公共 IP 地址的方法

使用 cmake 构建错误:找不到 -lpthreads

谁决定任何数据类型或 struct 的大小(取决于 32 位或 64 位)?

在 Linux 上用 C 语言读写串口

在Linux中使用空格设置环境变量

如何在 IE 中使用 Linux 进行测试

Linux(Ubuntu)终端-如何查看以前的页面不再可见