3

This question already has an answer here:

I want to replace multiple string patterns with a different set of predefined strings.

For example:

Input:

This sentence will be converted to something different. This sentence can contain same words.

Output:

These words need to be replaced with something different. These words can contain same alphabets. 

So here I want to convert in below pattern.

  • This =>These
  • sentence =>word
  • will =>need to
  • converted=>replaced
  • to => with
  • words => alphabets

Let me know if it can be done.

marked as duplicate by don_crissti, Stephen Rauch, G-Man, roaima, user259412 Nov 14 '17 at 5:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • What about sed 's/This/These/g' input_file or sed 's/This/These/g' <<< input_string respectively? – dessert Nov 13 '17 at 19:31
  • 1
    Yes, this can be done in sed.  It’s fairly simple, aside from the issue of cascading substitution (you want to avoid replacing “sentences” with “alphabets”). What have you tried? – G-Man Nov 13 '17 at 19:31
2

If your data is in the file data.txt (for instance) then you could use sed inside a for-loop. Maybe something like this:

replacements=(
    This:These
    sentence:word
    will:need to
    converted:repalced
    to:with
    words:alphabets
)

for row in "${replacements[@]}"; do
    original="$(echo $row | cut -d: -f1)";
    new="$(echo $row | cut -d: -f2)";
    sed -i -e "s/${original}/${new}/g" data.txt;
done

Not the answer you're looking for? Browse other questions tagged or ask your own question.