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?
Using Awk command We can use the built-in functions length and substr of awk command to delete the last character in a text.
sed 's/\(. *\),/\1/' file will remove last , in all lines in the file.
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\nline 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:
-i ''
instead of just -i
; for an overview of the pitfalls associated with -i
, see the bottom half of this answer.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With