5

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.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • 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 Says 'Reinstate Monica' Nov 13 '17 at 19:31

1 Answers1

3

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
dessert
  • 1,687
igal
  • 9,886