0

Say I have two files: - data.txt - report.txt

The report contains a text with some "placeholders", example:

HPLC results for sample: <insert-sample-id-here>, elements analyzed: <insert-element-name>

The data file contains a series of "key/value" lines:

sampleID: 123456abc
elementName: genericThickeningAgent

Not a computer whiz here, but I know the task of "find and replace" can be automated by the computer; What sort of command should be used to "rewrite report.txt after replacing the placeholders with the value of the matching pairs from my data file"?

kamituel
  • 34,606
  • 6
  • 81
  • 98
LabJem
  • 3
  • 1

1 Answers1

0

In the current form of the file, it would be hard to match values from data file to placeholders in report file, because placeholder <insert-sample-id-here> is different than sampleID from data.txt. The same for <insert-element-name> being not equal to elementName.

But assuming you have data.txt in a different form:

insert-sample-id-here: 123456abc
insert-element-name: genericThickeningAgent

(so if keys in data.txt are matching placeholders in report.txt) you can use this command:

$ perl -ne 'print "s/<$1>/$2/g\n" if /^(.*?):\s+(.*)$/' data.txt | \
    xargs -I% perl -p -i -w -e "%" report.txt

Which will replace all the placeholders in report.txt:

$ cat report.txt
results for sample: 123456abc, elements analyzed: genericThickeningAgent
kamituel
  • 34,606
  • 6
  • 81
  • 98
  • Wow this is actually more than I could have asked for! I thought it would be necessary to write the "find and replace" for each pair. I'll see if it's possible to change the report template. Thanks a lot for your solution, it's so good! – LabJem Mar 20 '13 at 07:33