Output to an existing file, and replace strings with arguments?

michaelsanford

Translator, Web Developer
That subject line is a bit convoluted, I admit.

What I'm trying to do is have an existing file act as a template, and then use a script to change strings in the file to other strings.

I'm not up on my C, but I'm thinking of a printf-style output. The argument structure is probably wrong, but it's something like printf('I am %A years old', $age);

I have a file full of %As and other formatting characters, and I want to replace the %As with a variable value, as a static file.

Is this simple? I can find the instances easily enough with grep, but I don't know how to replace the string.

Any help is appreciated, if you can decode this garbled explanation :rolleyes:
 
here's how I would approach this: a two part process, where the first process parses your data files, inserting variables names into each field:

( while read field1 field2 field3 field4 ; do
echo "f1='$field1'; f2='$field2'; f3='$field3'"
) < input-data-file > tempfile

then in a second loop, use the tempfile as input, feed it to the eval command, then simply substitute all occurances of, say, '$f1' with the actual value of the variable f1:

( while read inputline ; do
eval $inputline
sed "s/\$f1/$f1/g;s/\$f2/$f2/g;s/\$f3/$f3/g" < templatefile
) < tempfile

I hope that makes sense. It might be slightly off with syntax since this is top of my head, but as long as your datafile is well formed (e.g., there's a common delimiter between fields (if it's not a space, change the IFS value to use that instead, btw).

Cheers and good luck!
 
Back
Top