Reputation: 828
How to replace the last matching dot
?
for example, I'd like to change test.jpg to test.th.jpg
what I've tried:
echo "test.jpg" | sed 's@[^\.]*$@\.th.@g'
Upvotes: 0
Views: 2941
Reputation: 45313
Using pure bash
$ str="test.abc.jpg"
$ echo ${str%.*}.th.jpg
test.abc.th.jpg
Upvotes: 1
Reputation: 25609
if you have Ruby on your system
echo test.jpg | ruby -e 'x=gets.split(".");x.insert(-2,"th"); puts x.join(".")'
Upvotes: 0
Reputation: 4267
You can also use awk
, prepend "th." to the last field
$ awk 'BEGIN{FS=OFS="."}$NF="th."$NF' <<< "test.jpg"
test.th.jpg
Upvotes: 1
Reputation: 195219
kent$ sed 's/[^.]*$/th.&/' <<<"test.jpg"
test.th.jpg
or
kent$ sed 's/.*\./&th./' <<<"test.jpg"
test.th.jpg
or
kent$ awk -F. -v OFS="." '$NF="th."$NF' <<< "test.jpg"
test.th.jpg
Upvotes: 2
Reputation: 3999
This should work:
$ echo "test.jpg" | sed 's/\.\([^.]*\)$/.th.\1/'
It gives:
test.th.jpg
Explanation:
\. literal dot
\( start capturing group
[^.] any character except dot
* zero or more
\) close capturing group
$ end of line
In the replacement \1
replaces the content of the first capturing group :)
Upvotes: 7