Dimple
Dimple

Reputation: 111

How to find and replace data of file using shell script

My filename is myfile.txt and i want to replace some data inside it using shell script. I want to replace ScriptPathPC=\Myfile\file_core into ScriptPathPC=./file_core/ The code which i tried is

replace "ScriptPathPC=\Myfile\file_core" "ScriptPathPC=./file_core/" -- myfile.txt

But this command is working well with forward slash[/] and not with backward slash[]. Is there any other solution for this??

Upvotes: 2

Views: 211

Answers (1)

John1024
John1024

Reputation: 113814

Using replace

replace requires that the substitution be done perl-style:

replace 's|ScriptPathPC=\\Myfile\\file_core|ScriptPathPC=./file_core/|' file.txt 

The substitute command looks like s|old|new|. To prevent special treatment of them, we have to escape the backslashes.

Using sed

sed can similarly make changes. Here, we display the new file on stdout:

$ sed 's|ScriptPathPC=\\Myfile\\file_core|ScriptPathPC=./file_core/|' myfile.txt 
ScriptPathPC=./file_core/

Here, we change the old file in place:

sed -i 's|ScriptPathPC=\Myfile\file_core|ScriptPathPC=./file_core/|' myfile.txt

Upvotes: 1

Related Questions