Situation: I have a source HTML file, with some values which must be completed with data from another file.

Value that must be enriched is between a unique tag.


File 2 has several columns and many rows:

Info1 Mystring1 OtherInfo1 MoreInfo1
Info2 Mystring2 OtherInfo2 MoreInfo2
Info3 Mystring3 OtherInfo3 MoreInfo3

Afterwards I want to have my occurrences in HTML:

<Uniquetag>Mystring1 - Info1</uniquetag>

Both file1 and file2 are dynamic and periodically changed, I run my script after each change. It can happen that file1 does not contain the Uniquetag so nothing should be looked up. It is also possible that MyString1 cannot be found in file2. Nothing should be added in that case.

Can someone point me into the right direction on this one?

  • I'd use an XML or HTML parser. Most scripting languages should be able to handle that. Apr 26, 2016 at 17:08

2 Answers 2


Using "perl"

I'd do this with a Perl script as outlined by the following metacode:

for each line in file2:
    read line
    parse line into 4 fields with a pattern match
    build an associative array with $array{field2} = "field2 - field1"

slurp file1 into a single variable f

for each pattern match of /<UniqueTag>(match)</UniqueTag>/ in f:
    replace "match" with $array{match}

RedGrittyBrick has - pointed - out the pitfalls of trying to parse HTML reliably.

If, however, your HTML is as well-formatted as you show, then this may do the job:

while read -r one two rest
  expr="$expr; s/<uniquetag>$two<\/uniquetag>/<uniquetag>$two - $one<\/uniquetag>/"
done < file2
sed "$expr" sourcehtml > targethtml

... where you could, if you're comfortable with the results, change the sed expression to:

sed -i "$expr" sourcehtml

... to have it edit the sourcehtml file in-place.

There are many ways in which this could break, a few of which are:

  • either of the first two columns of file2 have a forward-slash or a single-quote
  • there are too many lines in file2, causing the sed expression to become too large (work-around by calling sed multiple times)
  • the tags are capitalized differently from "uniquetag" (notice I lower-cased the opening tag in my answer; upper-case it if that's wrong).

Sample run

Given your first three lines of "file2" and ...



The output is:

<uniquetag>Mystring1 - Info1</uniquetag>
<uniquetag>Mystring2 - Info2</uniquetag>
<uniquetag>Mystring3 - Info3</uniquetag>

You must log in to answer this question.

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