Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cutting last n character in a string using shell script

Tags:

bash

shell

cut

How can I remove the last n characters from a particular string using shell script?

This is my input:

ssl01:49188,,,
ssl01:49188,
ssl01:49188,,,,,
ssl01:49188,ssl999999:49188,,,,,
ssl01:49188,abcf999:49188,,,,,

The output should be in the following format:

ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188,ssl999999:49188
ssl01:49188,abcf999:49188
like image 715
anish Avatar asked Jan 15 '13 13:01

anish


People also ask

How do I remove the last character of a string in shell script?

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 I trim the last 3 characters of a string?

To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

How do I get the last 4 characters of a string in bash?

To access the last n characters of a string, we can use the parameter expansion syntax ${string: -n} in the Bash shell. -n is the number of characters we need to extract from the end of a string.


1 Answers

To answer the title of you question with specifies cutting last n character in a string, you can use the substring extraction feature in Bash.

me@home$ A="123456"
me@home$ echo ${A:0:-2}  # remove last 2 chars
1234

However, based on your examples you appear to want to remove all trailing commas, in which case you could use sed 's/,*$//'.

me@home$ echo "ssl01:49188,ssl999999:49188,,,,," | sed 's/,*$//'
ssl01:49188,ssl999999:49188

or, for a purely Bash solution, you could use substring removal:

me@home$ X="ssl01:49188,ssl999999:49188,,,,,"
me@home$ shopt -s extglob
me@home$ echo ${X%%+(,)}
ssl01:49188,ssl999999:49188

I would use the sed approach if the transformation needs to be applied to a whole file, and the bash substring removal approach if the target string is already in a bash variable.

like image 52
Shawn Chin Avatar answered Sep 20 '22 10:09

Shawn Chin