Adding lines at a particular location in a file.

Hi Experts,

Let us take a text file,say items.txt having the following data

jar
bottle
gum

tube
cereal
bag

I want to add the content of items.txt to another file say

#many lines not necessary
ingredients
#many line not necesary
ingredients

I want to append the data in fruits.txt to items.txt after the "First"
occurence of ingredient.

So the output shud be like:

#many lines not necessary
ingredients
jar
bottle
gum

tube
cereal
bag

#many line not necesary
ingredients

I have some idea like can be done by sed or awk,but instead can a shell script be written so that the values of fruits.txt be passed to items.txt ???
Doable ???

Thanks:)

#! /bin/bash
i=1
while read line
do
    if [ $(echo $line | grep ingredient) ] && [ $i -eq 1 ]
    then
        echo $line
        cat items.txt
        (( i++ ))
    else
        echo $line
    fi
done < fruits.txt
1 Like

Using shell builtins:

#!/bin/bash

while read line
do
        printf "%s\n" "$line"
        if [[ "$line" =~ "ingredient" ]]
        then
                [ -z "$flag" ] && cat items.txt
                flag=1
        fi
done < fruits.txt
1 Like

Thanks Balajesuri and Yoda..:slight_smile: