Question

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)

Was it helpful?

Solution 2

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

OTHER TIPS

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').

Try this:

string="name_1.23.ps.png"
array=(${string//./ })
echo "${array[0]}.${array[1]}.${array[2]}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top