13

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

input:

OpenOffice.org/m
openOffice.org/ozm
Pers.
Pfg.
phil.
Prof.
resp.
Roonstr./m
roonstr./ozm

desired output:

OpenOffice.org
openOffice.org
Pers
Pfg
phil
Prof
resp
Roonstr
roonstr

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/.$//'

13

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
| 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
2

Removing a character only if it is there is exactly the description of parameter expansions.

 $ var=path.
 $ echo "$var    ${var%.}"
 path.    path

The dot is not special in this case (a dot is special in a regex).

The other pattern could be removed with %/*:

 $ var=openOffice.org/ozm
 $ echo "${var%/*}"
 openOffice.org

To remove both:

 $ var=roonstr./ozm
 $ var=${var%/*}
 $ var=${var%.}
 $ echo "$var"
 roonstr

Of course, to work with a source file it is faster to use sed on the file.
Only remember to quote the dot (to match it literally, otherwise it means: any character).

 $ sed 's,/.*,,;s,\.$,,' file
| improve this answer | |
  • This should be the accepted answer. Needs more upvotes. – David Parks Nov 23 '19 at 18:42
0

Just slightly change your regular expression: to escape the . And you do not need grep

cat filename | cut -d"/" -f1 | sed 's/\.$//'
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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