Replace part of directory path that is a variable

Hi

I have a shell script and in it I need to replace some text in a path.

example: /opt/20150422_ABC/DC/10/82/filename.txt

The replacement will be the third value between /

Replace with  /opt/20150422_ABC/DBC/10/82/filename.txt

Not sure what the replacement would be.

Example

AA=/opt/20150422_ABC/DC/10/82/filename.txt
BB=DBC
CC=`echo $AA | sed 's@/\(.*\)/\(.*\)/\(.*\)/(.*)@/\1/\2/'$BB'\4@g'`

The code for the sed is not working and get the following

/opt/20150422_ABC/DC/10/DBC/filename.txt

It needs to be /opt/20150422_ABC/DBC/10/82/filename.txt

Thanks
LVL 1
mikeysmailbox1Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

woolmilkporcCommented:
AA=/opt/20150422_ABC/DC/10/82/filename.txt
BB=DBC
CC=$(echo $AA |sed 's@\(^/.*/.*/\).*\(/.*/.*/.*$\)@\1'$BB'\2@')

or, if the number of directories following the third one is unknown:

AA=/opt/20150422_ABC/DC/10/82/filename.txt
BB=DBC
CC=$(echo $AA |sed 's@\(^/[^/]*/[^/]*/\)[^/]*\(/.*$\)@\1'$BB'\2@')

Just for fun - here is good old awk:

AA=/opt/20150422_ABC/DC/10/82/filename.txt
BB=DBC
CC=$(echo $AA |awk -F/ -v B=$BB 'BEGIN {OFS="/"}
           {A=$5;for(n=6;n<=NF;n++) {A=A"/"$n} ;print $1,$2,$3,B,A}')
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mikeysmailbox1Author Commented:
Hi woolmikporc

Thanks that worked great.

Mike
0
simon3270Commented:
Just for fun, I tried replacing just the field to be changed:

    CC=$(echo $AA |awk -F/ -v B=$BB '{OFS="/";$4=B;print $0}')
0
ozoCommented:
#!/bin/bash
AA=/opt/20150422_ABC/DC/10/82/filename.txt
BB=DBC
CC=${AA%${AA#*/*/*/}}$BB/${AA#*/*/*/*/}
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Shell Scripting

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.