3

I have the issue to extract the x amount of characters from string and i have the difficulty enlarging the capability of the expression.

I have tried to use the sed command.

If i have the string example.com.db i need to keep "example.com",for that i use

sed 's/\.db//g' 

How to change expression so that i can use these kind of files too example.db.db.com.db.

in this case the end result i need is example.db.db.com

1
  • 2
    Please select one of the answers (all are correct) as accepted by clicking the tick mark on the left of the answer so that this issue can be marked as solved.. Commented Sep 18, 2015 at 8:19

4 Answers 4

7

you can use:

's/.db$//' 

alternatively you can use:

's/...$//' 

to remove the last 3 characters and

's/\.[^\.]*$//' 

to remove the everything after the last dot

2
  • 1
    +1, nitpickery: you don't need to escape most metacharacters within character classes, so in this case you could just do 's/\.[^.]*$//' Commented Sep 18, 2015 at 16:05
  • @kos: great catch. also $ seems unnecessary now that I look at it again. Commented Sep 18, 2015 at 18:09
4

You were close, use the Regex syntax $ to indicate the end of the line, also no need for the global (g) modifier as you are trying to find only one match :

sed 's/\.db$//' file.txt 

Example :

$ sed 's/\.db$//' <<<'example.db.db.com.db' example.db.db.com $ sed 's/\.db$//' <<<'example.db.com.db' example.db.com 
0
4

To remove last three characters from string

sed 's/.\{3\}$//' 

Example

% sed 's/.\{3\}$//' <<< "example.db.db.com.db" example.db.db.com 
2
  • You have to put an answer..don't you? ;) ..here, take my +1 :) Commented Sep 18, 2015 at 8:17
  • @heemayl Yes sir =) and I already have upvoted. Commented Sep 18, 2015 at 8:30
3

In sed, $ matches the end of line, so you can try

echo example.db.db.com.db | sed 's/\.db$//' 

Note that I backslashed the dot to match literally, otherwise it matches any character.

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.