linuxbashunixsed

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?


Solution

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

    sed '$ s/.$//' somefile
    

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

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

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

    Note: