LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Find and replace string ina file with specific condition (https://www.linuxquestions.org/questions/linux-newbie-8/find-and-replace-string-ina-file-with-specific-condition-4175598579/)

pradeepspa 01-30-2017 02:28 PM

Find and replace string ina file with specific condition
 
All,

I am trying to do this

1. Find line of a text file by grepping specific string
2. Once found, replace one of the string in that line with other.

Am using below script,

Quote:

#!/bin/bash

while read line
do
grep $line /tmp/export/raw-file.txt |sed 's/torspgw2/stjnspgw1/g;s/calspgw1/torspgw2/g'`

done </tmp/export/grep-file.txt
But looks like this script output the value as expected but not actually editing the file with new value. Is there anything i need to add further to make this work?

Turbocapitalist 01-30-2017 02:39 PM

grep is not necessary or useful there. Read up more on plain sed which can do conditionals like this:

Code:

#!/bin/bash
while read line
do
        sed "/$line/{s/torspgw2/stjnspgw1/g;s/calspgw1/torspgw2/g}" /tmp/export/raw-file.txt
done </tmp/export/grep-file.txt


grail 01-30-2017 02:59 PM

Sorry to say, but neither solution presented will change the original file (I think Turbocapitalist might have forgotten the file name ;) ).

Have a look at man sed for the -i option :)

pradeepspa 01-30-2017 03:05 PM

WOW!!! Awesome. Thanks guys.

Turbocapitalist 01-30-2017 03:09 PM

Quote:

Originally Posted by grail (Post 5662498)
(I think Turbocapitalist might have forgotten the file name ;) )

Thanks. Good catch.


All times are GMT -5. The time now is 08:22 PM.