That is, going from ABCD
-> ABC
$ 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.
In this method, you have to use the rev command. The rev command is used to reverse the line of string characterwise. Here, the rev command will reverse the string, and then the -c option will remove the first character. After this, the rev command will reverse the string again and you will get your output.
To remove the last n characters of a string, we can use the parameter expansion syntax ${str::-n} in the Bash shell. -n is the number of characters we need to remove from the end of a string.
You can try:
sed s'/.$//'
The regex used is .$
.
is a regex meta char to match anything (except newline)$
is the end of line anchor.By using the $
we force the .
to match the last char
This will remove the last char, be it anything:
$ echo ABCD | sed s'/.$//' ABC $ echo ABCD1 | sed s'/.$//' ABCD
But if you want to remove the last char, only if its an alphabet, you can do:
$ echo ABCD | sed s'/[a-zA-Z]$//' ABC $ echo ABCD1 | sed s'/[a-zA-Z]$//' ABCD1
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