-12

My file contains:

Pineapple
Apple
Banana
Rice
Grape
Watermelon
Orange
Apple
Banana
Rice
Mango
Pear
Plum
Banana
Rice
Cherry

I want to make it like this:

Pineapple
Apple
Banana
Rice
Grape
Watermelon
Orange
Apple
Banana
Olive
Mango
Pear
Plum
Banana
Rice
Cherry

I am, here, changing from "Rice" to "Olive", but only where the occurrence of "Rice" follows a match of a multi-line pattern; specifically where "Rice" occurs after the multi-line pattern:

Orange
Apple
Banana

I am open to using awk, perl, sed, or any other tool.

3
  • 2
    Have you tried anything?
    – Guy
    Dec 29, 2016 at 11:51
  • 2
    Please make a good faith attempt to solve the problem yourself first and then ask about specific problems with your attempts. Also, please admit that the question is homework.
    – phk
    Dec 29, 2016 at 12:41
  • This does seem like a homework question Mar 1, 2017 at 23:06

2 Answers 2

1

Perl does the job quite nicely:

perl -0pe 's/Orange\nApple\nBanana\n\KRice/Olive/' input.txt

You can exercise and test regexes on regex101.

0

One possible solution:

paste -d' ' -s myfile \
 | sed 's/\(Orange Apple Banana\) Rice/\1 Olive/g' \
 | tr ' ' '\n'

Explanation:

paste -d' ' -s myfile takes each line of myfile and pastes it serially (i.e., on a single line) separated by the delimiter (a space). Instead of input with one word per line, you now have input with all words on one line.

sed 's/\(Orange Apple Banana\) Rice/\1 Olive/g' searches through the input and replaces each occurrence of 'Orange Apple Banana Rice' with 'Orange Apple Banana Olive'.

tr ' ' '\n' translates all space characters in the input to newline characters, converting the single line of input back into the original format with one word per line.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .