6

I have file names that look something similar to this

name_1.23.ps.png

or

name_1.23.ps.best

or

name_1.23.ps

I want to take off the random file extensions on the end and be left with just

name_1.23.ps

Other questions similar to this use '.' as a delimator but this removes everything after name_1.

I want to do this on the command line (in tcsh or bash)

Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
user1958508
  • 605
  • 3
  • 7
  • 10

3 Answers3

11

check this if it works for your requirement:

sed

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

grep

grep -Po '.*(?=\.)'

test:

kent$  cat f
name_1.23.ps.png
name_1.23.ps.best
name_1.23.ps
name_1.23.ps

#sed:
kent$  sed 's/\.[^.]*$//' f
name_1.23.ps
name_1.23.ps
name_1.23
name_1.23

#grep
kent$  grep -Po '.*(?=\.)' f
name_1.23.ps
name_1.23.ps
name_1.23
name_1.23

EDIT from the comments. I feel it would be new requirement:

grep

kent$  grep -o '.*\.ps' f                                                                                         
name_1.23.ps
name_1.23.ps
name_1.23.ps
name_1.23.ps

sed

kent$  sed 's/\(.*\.ps\)\..*/\1/' f
name_1.23.ps
name_1.23.ps
name_1.23.ps
name_1.23.ps
Kent
  • 189,393
  • 32
  • 233
  • 301
11

We can use the bash string operation that deletes the shortest match of a glob patten from the back of a string. We will use ".*" for the glob pattern.

filename="name_1.23.ps.png"                                                      
echo ${filename%.*}                                                              
# the above output name_1.23.ps

This answer is more for my own reference as I come back to this page a few times. (It does not satisfy the OP's additional requirement of keeping the original string the same if it ends with only '.ps').

burnabyRails
  • 402
  • 9
  • 16
-1

Try this:

string="name_1.23.ps.png"
array=(${string//./ })
echo "${array[0]}.${array[1]}.${array[2]}"
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78