Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

How to remove last character only if it's there?


desired output:

I got it so far that only the dot is left but unfortunately the last sed command removes also letter g too: $ cat filename | grep "\." | cut -d"/" -f1 | sed 's/.$//'

share|improve this question

1 Answer 1

up vote 5 down vote accepted

You just need to escape the dot in your sed command and everything will be fine. Like this:

sed 's/\.$//'

Because in the case you don't escape it, .$ will match to any character at the end of string.

Also you can put all your sed + grep + cut into just one sed:

sed 's=/[^/]*$==;s/\.$//' filename
share|improve this answer
Great, thanks, works! :) I use a dictionary with over 300k lines so this is why I use grep "\." to get only the words with a dot there. – removelastdotonlyifitsthere Aug 15 '12 at 7:27
sed also can do it with smth like this: sed -n '/\./{s=/[^/]*$==;s/\.$//;p}. Anyway grep + sed will work much longer than just one sed. – rush Aug 15 '12 at 7:33
If it can be done with one sed it would be nice though. How to apply your last sed command? – removelastdotonlyifitsthere Aug 15 '12 at 7:36
sed 's/[./]\+[^./]*$//' – Peter.O Aug 15 '12 at 7:36
Thanks now I don't need cut, but grep is still there. A sed equivalent of my piped grep command would then remove the grep to,if it's possible, it would be nice. "Also you can put all your sed + grep + cut into just one sed" doesn't work for me, prints all the words? – removelastdotonlyifitsthere Aug 15 '12 at 7:41

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.