2

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,

3 Answers 3

1

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

sed "s/find/replace/g" filename
Sign up to request clarification or add additional context in comments.

7 Comments

s stands for substitute command to sed and g stands for global which means to substitute all occurences of the text matching the regular expression indicated by the find by the text indicated by replace
Thanks for your precious reply will try and update. Once again thanks.
As the find and replace portions appear to be paths, using a different delimiter will likely be helpful: sed 's!/path/one!/path/two!g
Hi @Vikas Nalwar, Works fine. Your help is really appreciated. Once again thanks.
Hi @Vikas Nalwar, For example: sed "s/raj/ravi/g" here ravi is placed in another file. The reason behind, i am getting the word as an input using "read word" and writing the word to another file. So i want to read the word "ravi" from other file and replaced to another file. Please help me on this.Please provide me the example
|
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.