Text replacement question: sed/awk/perl whatever
Hi all,
Apologies if this is really obvious or it's been answered before (I can't find it in the wiki or the forums). I need a way to replace a piece of text in a file1 with the contents of file2. In the file1, I already have a piece of 'placeholder' text, which is where the the contents of file2 are to be inserted. I've seen various things like this: Code:
perl -pi -e 's/find/replace/g' Code:
sed -e 's/find/replace/' file But what I can't figure out is how to get 'replace' to be the contents of a file, rather than a given string. <superfluous_detail> Specifically, what I'm trying to do is insert the base64 of file2 into an XML document (file1) which was generated using XSLT. But I coudn't find a way to do a base64 of a file in XSLT so I've used XSLT to insert a bit of placeholder text, and I hope to find a way of shell scripting the operation of inserting the base64 of file2 into the placeholder's position. In the question, I'm assuming that file2 already contains the base64 of the file I want by using the shell command for that, but if the solution could do the base64 operation inline on the original file that'd be super-cool. Not having to rely on another command would be very handy. </superfluous_detail> I'll be running any solution on Red Hat Enterprise Linux 3 and/or 5. Thanks in advance for any ideas. |
The elaborate way could be to 'SOMEVAR=`cat file2`; 'sed -i "s|SOMETERM|${SOMEVAR}|g" file1' but 'sed -i "s|SOMETERM|$(cat file2)|g" file1' works too. This means 'sed -i "s|SOMETERM|$(mimencode -b file2|xargs)|g" file1' should work too.
|
Hi unSpawn,
Thanks for the idea, and for the quick reply! I think it's pretty close, but I get this error when running it: Code:
sed: 1: "s|SOMETERM|< ...": unescaped newline inside substitute pattern Code:
#!/usr/bin/env bash Thanks. |
Quote:
|
Thanks,
I'll give that a go. |
You could replace a ^M character with \n in your $SOMEVAR replace pattern. You might want to use a different character than '*' if it might be in the replacement pattern file.
var=$(cat file2 | tr '\n' '*' | sed 's/*/\\n/g') |
Hi all,
I discovered that the machine in question is so old that it doesn't have mimeencode or similar. So I've had to use a Perl command instead. I also decided to split the process up so that it doesn't do an replace on the input file, so now it uses stdout to redirect the replaced version. Here's the code I've come up with - it seems to work. 'placeholder' is the placeholder text. $infile is the file we want to base64 $container is the file we want to insert the base64 version into. $container-final.xml will contain the final output. Code:
sed -e "s|placeholder|$(perl -MMIME::Base64 -0777 -ne 'print encode_base64($_)' < $infile | xargs)|g" $container > $container-final.xml |
All times are GMT -5. The time now is 03:59 PM. |