Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

linux - How can I remove the last character of a file in unix?

Say I have some arbitrary multi-line text file:

sometext
moretext
lastline

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

sed '$ s/.$//' somefile
  • $ 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/.$// 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.

  • 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

Note:

  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...