LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   using sed to replace multiple strings (http://www.linuxquestions.org/questions/linux-newbie-8/using-sed-to-replace-multiple-strings-4175459848/)

castor0troy 04-28-2013 02:56 AM

using sed to replace multiple strings
 
Hi Guys
I know this has been covered in the past but there is a small twist/

a.txt is
redcat
redhat
bluebat

b.txt is
cat mat
hat tat
.
.thousand keywords

i want to use sed to replace cat with mat[example] from b.txt

output should be
redmat
redtat
bluebat

iv tried the regular sed command but how do i do it for thousand of keywords?

thanks

jdkaye 04-28-2013 03:06 AM

Quote:

Originally Posted by castor0troy (Post 4940333)
iv tried the regular sed command but how do i do it for thousand of keywords?

thanks

Hi Castor,
Can you show us what you've go so far. It will make it easier to help you.
Ciao,
jdk

castor0troy 04-28-2013 03:09 AM

Hi
ive got the results using sed.
$sed 's/string1/string2/' file1 > file1


the questions is how do i incorprate file names in sed.
string1 and string 2 are in b.txt
example
string1=cat
string2=mat

allend 04-28-2013 03:10 AM

Use sed to make a sed interpreter script from your b.txt. http://www.grymoire.com/Unix/Sed.html#uh-20

castor0troy 04-28-2013 04:46 AM

thanks.
this link helped.

shivaa 04-28-2013 05:16 AM

Even you can replace the word cat with mat in vi editor, as:
Code:

~$ vi b.txt
:%s/cat/mat/g


theNbomr 04-28-2013 12:36 PM

allend's suggestion of creating a sed interpreter script is probably the definitive solution. Another possibility is to loop over all line entries in b.txt:
Code:

while read from to; do
  echo sed -i s/$from/$to/g a.txt
done < b.txt

This only works if the substitution text contains no whitespace. It is left as an exercise to the reader to make the script actually work on real data files. Test on backup data first.
--- rod.

David the H. 04-29-2013 11:42 AM

A trick I would probably use would be to run one sed command inside a process substitution, to reformat the file into a sed script that can be used directly in a second instance.

Code:

sed -f <( sed -r 's|(\w+) (\w+)|s/\1/\2/|' b.txt )  a.txt


All times are GMT -5. The time now is 08:55 AM.