How to get data from a file then populate the fields into other file using awk script?

Viewed 51

Is there any other way to get data from a file then populate the fields into other file by using any script file, such as awk? (sed script might be okay to use it) Note: it doesn't have to be using grep and find.

file1.txt

AAA Abcd
Watermelon Apple
8/25/19 11/24/19
4
55


file2.txt

[[letters_aaa]]
[[letters_abcd]]
[[fruit_names]]
[[date_start]]
[[date_end]]
[[four_hours]]
[[num_fiftyfive]]

merge into this one

AAA
Abcd
Watermelon Apple
8/25/19
11/24/19
4
55

I tried using awk script but I wasn't sure what to write after locating number of line. This script is all I can do:

BEGIN {
}
{
if(NR==1) {
  print $1 $2
}
1 Answers

It's 2AM here so I'm not sure if your question or my answer make any sense. It reads files in with RS="" so all fields must be filled, empty fields will break the output (in which case use RS="^$" and replace print with printf):

$ awk '
BEGIN {
    RS=""                                
}
NR==FNR {                                  # store file2 as template
    t=$0
    next
}
{
    sub(/\[\[letters_aaa\]\]/,$1,t)        # replace template items with file fields
    sub(/\[\[letters_abcd\]\]/,$2,t)
    for(i=3;i<=NF-4;i++)
        fruit=fruit (fruit==""?"":OFS) $i  # dealing with space in names
    sub(/\[\[fruit_names\]\]/,fruit,t)
    sub(/\[\[date_start\]\]/,$(NF-3),t)
    sub(/\[\[date_end\]\]/,$(NF-2),t)
    sub(/\[\[four_hours\]\]/,$(NF-1),t)
    sub(/\[\[num_fiftyfive\]\]/,$NF,t)
    print t
}' file2 file1
Related