preppypoof preppypoof - 1 month ago 9
Bash Question

Inserting contents of one file into another file based on specific string

I'm trying to write a bash script that does the following:

1) Read the contents of one file (f1.txt)

2) For each line that starts with "<", but does not contain "start" or "item", insert the entire contents of a second file (f2.txt) in the line after. This change must be done in the original file, f1.txt

For example:

f1.txt:

<start>
<name1>
<item>
stuff
</item>
</name1>
<susan>
<item>
stuff
</item>
</susan>
</start>


f2.txt:

HELLO
WORLD


results, f1.txt:

<start>
<name1>
HELLO
WORLD
<item>
stuff
</item>
</name1>
<susan>
HELLO
WORLD
<item>
stuff
</item>
</susan>
</start>


How should I go about solving this? Should I read line-by-line, or even character-by-character?

Answer

You can use this awk command:

awk 'NR==FNR {if (a) a=a ORS $0; else a=$0; next}
     /^ *<[^\/]/ && !/<(start|item)>/ {$0=$0 ORS a}1' f2.txt f1.txt
<start>
  <name1>
HELLO
WORLD
    <item>
      stuff
    </item>
  </name1>
  <susan>
HELLO
WORLD
    <item>
      stuff
    </item>
  </susan>
</start>