Warm tip: This article is reproduced from stackoverflow.com, please click
awk sed text gawk ed

Using gawk to Replace a Pattern of Text with the Contents of a File Whose Filename is Inside the Tex

发布于 2020-04-11 12:01:48

I am trying to replace text inside a text file according to a certain criteria.

For example, if I have three text files, with outer.txt containing:

   Blah Blah Blah
   INCLUDE inner1.txt
   Etcetera Etcetera
   INCLUDE inner2.txt
   end of file

And inner1.txt containing:

  contents of inner1

And inner2.txt containing:

  contents of inner2

At the end of the replacement, the outer.txt file would look like:

    Blah Blah Blah
    contents of inner1
    Etcetera Etcetera
    contents of inner2
    end of file

The overall pattern would be that for every instance of the word "INCLUDE", replace that entire line with the contents of the file whose filename immediately follows that instance of "INCLUDE", which in one case would be inner1.txt and in the second case would be inner2.txt.

Put more simply, is it possible for gawk to be able to determine which text file is to be embedded into the outer text file based on the very contents to be replaced in the outer text file?

Questioner
gawk_Nube
Viewed
45
Cyrus 2018-05-10 03:39

With GNU awk:

awk --load readfile '{if ($1=="INCLUDE") {printf readfile($2)} else print}' outer.txt