how to use sed to replace from last 3 characters from string

22,440

Solution 1

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

Solution 2

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

Solution 3

To remove last three characters from string

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

Example

% sed 's/.\{3\}$//' <<< "example.db.db.com.db"
example.db.db.com

Solution 4

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.

Share:
22,440

Related videos on Youtube

Vitalik Jimbei
Author by

Vitalik Jimbei

Updated on September 18, 2022

Comments

  • Vitalik Jimbei
    Vitalik Jimbei over 1 year

    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

    • heemayl
      heemayl over 8 years
      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..
  • A.B.
    A.B. over 8 years
    @heemayl Yes sir =) and I already have upvoted.
  • kos
    kos over 8 years
    +1, nitpickery: you don't need to escape most metacharacters within character classes, so in this case you could just do 's/\.[^.]*$//'
  • Admin
    Admin over 8 years
    @kos: great catch. also $ seems unnecessary now that I look at it again.