Sed Delete Last Character

by Vivek Gite on July 14, 2007 · 5 comments

How do I delete a last character from input line under UNIX / Linux using sed tool? My sample scientific input data line is as follows and I'd like to get rid of last + character only:

379100.46+521870.11+363838.75+382869.59+

How do I used sed to delete last + character?

Use it as follows:
echo "379100.46+521870.11+363838.75+382869.59+" | sed '$s/.$//'
If you would like to calculate final result, enter:
echo "379100.46+521870.11+363838.75+382869.59+" | sed '$s/.$//' | bc -l

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 5 comments… read them below or add one }

1 Mani October 18, 2010

Hi,

Please help me for this.

input : 379100.46+521870.11+363838.75+382869.59
output : 379100.46+521870.11
I would like remove last the character based last two delimiter. Please help me.

Reply

2 jupiter2005ster March 18, 2011

Try it:

echo $text | sed -e ‘s/\(.*\)../\1/’

Reply

3 Konrad Höffner July 22, 2011

That was exactly what I was searching for, thanks!
Can you explain why it works, though? I use sed quite often but I don’t know what the

$s/.$

does, I always do

sed "s|text|replacement|g"

.

Reply

4 SilversleevesX November 14, 2011

Konrad,

The “$” (dollar sign; I usually call it “cash”) is a marker or flag that tells sed to jump to the end of a line and edit something in the vicinity of the last character in it. I believe its counterpart for the beginning of a line is “^” (up-pointing carat), but don’t quote me on that. These markers are part of the sed program itself, which can present a problem only when the characters they represent are the ones you want to “sed out” of a string — sometimes even escaping them doesn’t work in those instances.

Hope this helps.

BZT

Reply

5 SilversleevesX November 14, 2011

mandre on ivorde.ro offers other approaches here.
http://www.ivorde.ro/How_to_remove_first_last_character_from_a_string_using_SED-75.html

Evidently the ‘$s’ syntax at the beginning of the sed command isn’t common or even necessary. A simple

sed ‘s/.$//’

usually suffices.

(The above is from one of the comments, not ivorde’s primary text.)

BZT

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 3 + 2 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: