如何在unix中删除文件的最后一个字符? [英] How can I remove the last character of a file in unix?

查看:26
本文介绍了如何在unix中删除文件的最后一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I have some arbitrary multi-line text file:

sometext
moretext
lastline

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

How can I remove only the last character (the e, not the newline or null) of the file without making the text file invalid?

推荐答案

更简单的方法(输出到标准输出,不更新输入文件):

A simpler approach (outputs to stdout, doesn't update the input file):

sed '$ s/.$//' somefile

  • $ 是只匹配最后输入行的 Sed 地址,从而导致执行以下函数调用(s/.$//)仅在最后一行.

    • $ is a Sed address that matches the last input line only, thus causing the following function call (s/.$//) to be executed on the last line only.

      s/.$// 用空字符串替换(在本例中为 last)行的最后一个字符;即,有效地删除最后一个字符.(换行前)就行了.
      . 匹配该行中的任何字符,紧随其后的 $ 将匹配锚定到该行的末尾;请注意 $ 在这个 正则表达式 中的使用在概念上是如何相关的,但在技术上与之前将 $ 用作 Sed 不同地址.

      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):

      Example with stdin input (assumes Bash, Ksh, or Zsh):

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

    • 更新输入文件(如果输入文件是符号链接,则不要使用):

      To update the input file too (do not use if the input file is a symlink):

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

      注意:

      • 在 macOS 上,您必须使用 -i '' 而不是 -i;有关与 -i 相关的陷阱的概述,请参阅此答案的下半部分.
      • 如果您需要处理非常大的输入文件和/或性能/磁盘使用是一个问题并且您正在使用 GNU 实用程序 (Linux),请参阅ImHere 的有用答案.
      • On macOS, you'd have to use -i '' instead of just -i; for an overview of the pitfalls associated with -i, see the bottom half of this answer.
      • If you need to process very large input files and/or performance / disk usage are a concern and you're using GNU utilities (Linux), see ImHere's helpful answer.

      这篇关于如何在unix中删除文件的最后一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆