I have been looking for a way to do this with sed and awk but could not get the results I need. I have a single file with multiple lines in which I need to replace a './' with '/home/'.
For example:./tmp/1.jpg
./tmp/2.jpg
Should become:/home/tmp/1.jpg
/home/tmp/1.jpg
Any help is apprecaited!
sed 's/\./\/home/g' file > newfile
cheers,
Devaraj Takhellambam
This is where I got stuck with sed and moved onto awk...
Using your suggestion took this source:
./999/999.jpg
And generated the following output:
home/999/999homejpg
This removed the first '/' and replaced the second instance of the '.' (replacing the second instance of '.' with 'home'). I need to replace './' with '/home/' or a longer directory like '/home/username/'.
Try This ...
sed "s/\.\/tmp/\/home\/tmp/g" filename > newfile
That actually didn't have any effect...
brianm:
This is where I got stuck with sed and moved onto awk...
Using your suggestion took this source:
./999/999.jpg
And generated the following output:
home/999/999homejpg
This removed the first '/' and replaced the second instance of the '.' (replacing the second instance of '.' with 'home'). I need to replace './' with '/home/' or a longer directory like '/home/username/'.
Ah, I didn't notice the . extension. you can searc for ./ and replace it with /home/
sed 's/\.\//\/home\//g' filename > outfile
or
sed 's/^\.\//\/home\//g' filename > outfile
cheers,
Devaraj Takhellambam
echo './tmp/1.jpg' | sed 's#^[.]#/home#'
Can you briefly explain this? I don't understand what prevents this from replacing all instances of '.'.
devtakh, although it took me a minute to figure out how to use this witha longer path, it works very well. Thank you!
brianm:
Can you briefly explain this? I don't understand what prevents this from replacing all instances of '.'.
devtakh, although it took me a minute to figure out how to use this witha longer path, it works very well. Thank you!
echo './tmp/1.jpg' | sed 's#^[.]#/home#'
'^' signifies 'the beginning of a line.
But removing the ^ still only replaces the first instance?
Lastly, I'm trying to remove the 1.jpg and just leave /home/tmp/, but I am not able to acheive this doing the following:
echo '/home/1.jpg' | sed 's#/*[.]jpg##'
I am left with the trailing '1'.
if you have Python, here's an alternative
import fileinput
for line in fileinput.FileInput("file",inplace=1):
line=line.strip()
if line.startswith("./"):
print line.replace("./","/home/")
output:
# ./test.py
/home/tmp/1.jpg
/home/tmp/2.jpg
brianm:
But removing the ^ still only replaces the first instance?
Lastly, I'm trying to remove the 1.jpg and just leave /home/tmp/, but I am not able to acheive this doing the following:
echo '/home/1.jpg' | sed 's#/*[.]jpg##'
I am left with the trailing '1'.
echo '/home/1.jpg' | sed 's#\(.*\)/.*$#\1#'