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)
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
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]}"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.