user626206
user626206

Reputation: 687

How to search and replace a content of a file using shell script?

I have started learning shell scripting a few days ago. My scenario is, i have to search and replace a content which exists in different lines in a file using shell script.

For Example, I have mentioned the path name in a file :-

path = /home/test/db

My name is so and

path = /home/test/db

Here, The path name "/home" has to be replaced with "/Second" in specified lines of the file using shell script. By using "sed" command i have tried and replaced the content of the file has only one line but i am struggling with replacing which is present in different lines. I am using "If" condition in shell script.Please do help me in resolving this case.

Thanks and Regards,

Upvotes: 2

Views: 11190

Answers (3)

vikram jeet singh
vikram jeet singh

Reputation: 3516

The below mentioned code will search all JS files under "search_folder_name". It will find "version_number" for all occurrences in the defined folder and replace it with respective value defined. Save the below menioned code in .sh file say, test.sh

#!/bin/bash
versionNo=0.0.1
find ./search_folder_name/ -name \*.js -type f -print0 | while read -d $'\0' file; do
    echo "Processing $file"
    sed -i '' 's/{version_number}/'$versionNo'/g' $file
done

Upvotes: 0

Paritosh Yadav
Paritosh Yadav

Reputation: 51

sed -i 's/original/new/g' file.txt

Explanation:

sed = Stream EDitor -i = in-place (i.e. save back to the original file) The command string:

s = the substitute command

original = a regular expression describing the word to replace (or just the word itself)

new = the text to replace it with

g = global (i.e. replace all and not just the first occurrence)

file.txt = the file name

Upvotes: 0

Drona
Drona

Reputation: 7234

I believe you missed the g option in your sed command. See below

sed "s/find/replace/g" filename

Upvotes: 1

Related Questions