Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shave off last character using sed?

That is, going from ABCD -> ABC

like image 551
Roger Moore Avatar asked Sep 09 '10 09:09

Roger Moore


People also ask

How do I remove the last character in sed?

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

How do I remove the last character in Linux?

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.

How do you trim the last character of a shell?

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.


1 Answers

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 
like image 133
codaddict Avatar answered Sep 19 '22 13:09

codaddict