# How to replace string containing file path using sed

I want to replace a file path to other using sed. I am attaching a small part of my file Kindly help

source file :

Dir=D:\test\foo
Dir=D:\test\bar


the result should look like this

Dir=E:\test1\foo
Dir=E:\test1\bar


Using sed with pattern grouping:

sed -r 's/(.*=)D(:\$^$+)(\\.*)/\1E\21\3/' file.txt

• All () are indicating pattern groups, the purpose of grouping is to use them in the replacement by just using \# reference (replace # with group number, incrementing from 1, left to right)

• (.*=) will match the portion before first D, this is referenced as group 1 i.e. \1 in replacement

• (:\$^$+) matches upto the second \ after D, this is \2

• (\\.*) matches everything else after second \ (including), this is \3

Example:

$cat file.txt Dir=D:\test\foo Dir=D:\test\bar$ sed -r 's/(.*=)D(:\$^$+)(\\.*)/\1E\21\3/' file.txt
Dir=E:\test1\foo
Dir=E:\test1\bar


If you have multiple occurrences and you want to replace them all:

$cat file.txt Dir=D:\test\foo Dir=D:\bar\foo Dir=D:\test\bar$ sed -r 's/D(:\\)[^\]+/E\1test1/g' file.txt
Dir=E:\test1\foo Dir=E:\test1\foo
Dir=E:\test1\bar

• Thanks, it worked and i also want to know is there any way we can replace the whole file path with other by mentioning the path in braces or something like that, so that it will be more catchy @heemayl – Rooney Apr 18 '16 at 8:53
• @Rooney Could you please give an example and your desired output from that.. – heemayl Apr 18 '16 at 8:54
• Could you explain the sed please . – monitor35 Apr 18 '16 at 8:56
• sed -i 's|D:\test|E:\test1|g' file i tried this but it didn't work. I meant something like this. Mentioning the whole path and replacing it with other. – Rooney Apr 18 '16 at 9:00
• @monitor35 Added.. – heemayl Apr 18 '16 at 9:01