16

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

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175

3 Answers3

16

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
rush
  • 27,055
  • 7
  • 87
  • 112
4

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
0

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

cat filename | cut -d"/" -f1 | sed 's/\.$//'
medifle
  • 1
  • 1