anish
anish

Reputation: 7412

How can I remove trailing characters from a string using shell script?

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

Upvotes: 15

Views: 71481

Answers (4)

Shawn Chin
Shawn Chin

Reputation: 86844

To answer the first line of your question which asks to "remove the last n characters from a string", you can use the substring extraction feature in Bash:

A="123456"
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/,*$//'.

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

ssl01:49188,ssl999999:49188

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

X="ssl01:49188,ssl999999:49188,,,,,"
shopt -s extglob
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.

Upvotes: 43

Vijay
Vijay

Reputation: 67211

I guess you need to remove those unnecessary ,'s

sed 's/,,//g;s/\,$//g' your_file

tested:

> cat temp
ssl01:49188,,,
ssl01:49188,
ssl01:49188,,,,,
ssl01:49188,,,
ssl01:49188,
ssl01:49188,,,,,
ssl01:49188,ssl999999:49188,,,,,
ssl01:49188,abcf999:49188,,,,,
> sed 's/,,//g;s/\,$//g' temp
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188,ssl999999:49188
ssl01:49188,abcf999:49188
> 

Upvotes: 1

Guru
Guru

Reputation: 16974

Using sed:

sed 's/,,*$//g' file 

Upvotes: 1

cmbuckley
cmbuckley

Reputation: 42458

With sed:

sed 's/,\+$//' file

Upvotes: 13

Related Questions