Incorporate a file in another with AWK

Sep. 21, 2012

Hello.

Recently, I had to replace a string of characters by a text file content.

Example : I want to replace “##__youpi_tralala__##” by the content of the text file called “youpi_tralala”.

I tried with sed, but it wasn’t reliable, as sed tried to execute the text file content.

So I worked with my best friend AWK.

Here is the result, the script called include_file.awk :

{ str=$0 where=match(str,regexp) if (where) { while ((“cat “file) | getline tstr > 0) { if (newstr == “”) { newstr=tstr } else { newstr=newstr”\n"tstr } } close (tstr) sub(regexp,newstr,str) } print str }

It’s a beautiful AWK script, which can be launched like this : awk -v regexp=“awesome regexp” -v file=/path/to/the/included/file -f include_file.awk text_file_with_the_regex

I use it in LaTeX, to debug some includes, to see if the file content or the include which is the origin of the issue.

Here is an example :

awk -v regexp="^%%__part1__%%$” -v file=includes/part1.tex -f include_file.awk document.tex | pdflatex -jobname=document

Here, the string placed in the document.tex file is “%%__part1__%%”.

That’s all folks :D.