Orlo
Orlo

Reputation: 828

Sed: replace last dot

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

Answers (5)

BMW
BMW

Reputation: 45313

Using pure bash

$ str="test.abc.jpg"

$ echo ${str%.*}.th.jpg
test.abc.th.jpg

Upvotes: 1

kurumi
kurumi

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

ray
ray

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

Kent
Kent

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

Ju Liu
Ju Liu

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

Related Questions