using sed to replace a part of string

Hi,

I have files that are named front1.txt to front999.txt. They are all in the same directory. To change "front" to "back", I am doing something like this.

for file in .txt; do
new=`echo $file | sed 's/^[a-z]*[A-Z]
/back/g'`
mv $file $new
done

My problem is what if files are named 1front1.txt to 999front999.txt? How would I just change the "front" part of the string?

Thanks in advance!

-j.

new=`echo $file | sed 's/front/back/'`

What if you want to replace a word (no numbers) that's surrounded by number(s)?

For example, atfront111front111front.txt. I'd like to replace only the second "front".

Add a /g at the end to make it global otherwise it matches just the first instance. For example:

echo atfront111front111front.txt | sed -e"s/front/back/g"

Cheers,

Keith

kduffin, I think that csejl is just playing yo-yo with us. But if you want to play, you're supposed to nail only the the 2nd occurrence of "front" while leaving occurrences 1 and 3 intact. :rolleyes:

Of course, csejl will then come back and say "what I really meant..." :slight_smile:

To replace the second "front"...

echo atfront111front111front.txt | sed 's/front/back/2'

To to replace a word which is surrounded by number(s)...

echo atfront111front111front.txt | sed 's/\([0-9][0-9]*\)[A-Za-z][A-Za-z]*\([0-9][0-9]*\)/\1back\2/'

...which can be written more consisely (if your version of sed supports it)...

echo atfront111front111front.txt | sed 's/\([0-9]+\)[A-Za-z]+\([0-9]+\)/\1back\2/'

Thanks. That's exactly what I was looking for!

-j.