awk/sed string search and replace

Need help with either sed or awk to acheive the following

file1
-----

In the amazon forest
The bats eat all the time...
mon tue wed they would eat berries

In the tropical forest
The bats eat all the time...
on wed bats eat nuts

In the rain forest
The bats eat all the time...
on mon tue wed bats eat nats

In the above file I would like to look for the words "tropical forest" and then look for the word "wed"
if it exists then
add a "#" in front of the line and add a new line with the text "on mon tue wed they would eat berries"

The result would look like this

In the amazon forest
The bats eat all the time...
mon tue wed they would eat berries

In the tropical forest
The bats eat all the time...
#on wed bats eat nuts
on mon tue wed they would eat berries

In the rain forest
The bats eat all the time...
on mon tue wed bats eat nats

Your input is much appreciated !
Thanks

There are several questions that can be asked and many scenarios that can be created based on your description.

In any event, not to get too complicated, here is one possible solution based exactly on your sample data:

!/usr/bin/ksh
typeset -i mCount
while read mLine
do
  mCount=$(echo ${mLine} | egrep -c 'tropical forest')
  if [[ ${mCount} -ne 0 ]]; then
    mFlag='Y'
  fi
  if [[ "${mFlag}" = "Y" ]]; then
    if [[ "${mLine}" = "" ]]; then
      mFlag='N'
    else
      mCount=$(echo ${mLine} | egrep -c 'wed')
      if [[ ${mCount} -ne 0 ]]; then
        echo '#'${mLine}
        echo 'on mon tue wed they would eat berries'
        mFlag='N'
        continue
      fi
    fi
  fi
  echo ${mLine}
done < input_file
1 Like

A similar solution using sed:

sed '/tropical forest/n;s/\(.*on wed.*\)/#\1\non mon tue wed they would eat berries/1' infile

This pretty much looks like homework, though.

1 Like