stack_A
stack_A

Reputation: 763

remove last substring from string

I would like to remove the last subsrting from string. the pattern of string is :

str1.str2.strn-1.{i}.strn

and the desired result is :

str1.str2.strn-1.{i}.

I tried with shell echo $str |sed -e 's/\.*$//' but it doesn't work

what is the best method to do that

Upvotes: 1

Views: 890

Answers (4)

stack_A
stack_A

Reputation: 763

The solution with tcl

regsub -- {[^.]+$} $str {} string

[^.]+$ match the last '.' appended with any string at the end of $str

Upvotes: 0

linraen_das
linraen_das

Reputation: 16

Let us use the fact that strings are dot-separated. Here is a pure Tcl solution (s is original string):

set s "[file rootname $s]."

or

set s [file rootname $s]
append s "."

According to file(n) manpage, file rootname returns

...all of the characters in name up to but not including the last “.” character in the last component of name. If the last component of name does not contain a dot, then returns name

Upvotes: 0

Rob Davis
Rob Davis

Reputation: 15802

A short, simple solution that uses standard sed, without using extended regular expressions:

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

which says to remove every non-dot character from the end of the line. A few things to note:

  1. Typically a dot (aka period) means "any character," but inside a bracket expression, it matches only a literal dot, so there's no need to escape it with a backslash.
  2. Asterisk means "match zero or more," and by default the asterisk is greedy, meaning it will match as many characters as it can.

So the command says to replace as many non-dots as possible at the end of the line with nothing.

Upvotes: 1

Code Different
Code Different

Reputation: 93181

The -e switch is to add editing command. You only have 1 command so there's no need to use it. Instead, you want the -E flag to tell sed to use modern regular expression. Try this:

echo $str | sed -E 's/[^.]+$//'

[^.]+$ matches any character between the last dot and end of line.

Upvotes: 3

Related Questions