hi,
i have variable value as follows
val="/dir1/dir2/dir3/dir4/dir5/dir6/file1"
it is pointing to some file location.
and i have another file as
../../dir4/file3
../../dir4/dir5/file4
../../dir7/file5
i want the output as
/dir1/dir2/dir3/dir4/file3
/dir1/dir2/dir3/dir4/dir5/file4
/dir1/dir2/dir3/dir7/file5
please anybody help me.
If I got your purpose right, you may try this:
sed "s|^\.\./\.\.|$(echo "$val"|cut -c 1-15)|g" <filename>
What would be your required output if one of the lines in the file was
../../dir5/file5
????
/dir1/dir2/dir3/dir5/file5
OR
/dir1/dir2/dir3/dir4/dir5/file5
?
for example i wrote the directories names as dir1, dir2 and so on.
those directories names are different.
i need the script for different directory names but no.of directories to be replaced is 3 as
if variable is val="/dir1/dir2/dir3/dir4/dir5/dir6/file1" then i have to replace ../../ with /dir1/dir2/dir3/
if variable is val="/home/gopu/india/dir4/dir5/dir6/file1" then i have to replace ../../ with /home/gopu/india/
Then try
sed "s|^\.\./\.\.|$(echo "$val"|cut -d/ -f1-4)|g" <filename>
it's working fine . thank you elixir_sinari
I always worry about marking relative references in scripts. If something doesn't exist, a cd will just refuse and unless you carefully manage errors, then you could end up damaging important files. Consider:-
cd /etc
grep -v bankhost hosts > dr_test_hosts
cd /disaster
rm *
cp -pR /etc/* .
This would (probably in a bad way anyway) remove a sensitive remote host address from /etc/hosts in preparation for a DR test to reduce the risk of actually sending data to the bank. Of course, if you run this and /disaster does not exist then you empty /etc, which could be a little awkward, to say the least.
Could it be a better plan to have a variable made of several others, such as:
maindir=/dir1/dir2
val=${maindir}/dir3/dir4/file1
...do something...
val=${maindir}/dir3/newdir4/file2
...do something...
val=${maindir}/dir3/bigdir4/file3
...do something...
You would still have to check that these exist, of course, but it reduces the risk of a typing error and one action compounding on another.
Maybe I'm paranoid, but unless you consider every possible action and error, then it's a dangerous game. I've been bitten in the past, so I can't claim perfection, just learning from experience.
I hope that this helps,
Robin
Liverpool/Blackburn
UK
one small thing elixir_sinari
if in the file there are morethan ../../ values like ../../../ or ../../../../
then how to modify the sed command. i tried as follows but it is not working
sed "s|^(\.\./)* | $(echo "$val"|cut -d/ -f1-4)|g" filename
Something on these lines...
sed -n "s|^\(\.\./\)\{2\}|$(echo "$val"|cut -d/ -f1-4)/|gp" <filename>
Just change the value in the interval regular expression....the number in boldface...