dancer
dancer

Reputation: 1

How to combine two files by inserting lines at multiple different locations with awk/sed

I have two files: file1.txt and file2.txt. The first one, file1.txt, contains lots of information and in irregular intervals it shows the word TIMESTEP. The second one, file2.txt, on the other hand, contains only a single column of integer values. I would like to parse through file1.txt, find the lines with TIMESTEP and replace the following line with the next line from file2.txt. As an example:

file1.txt

ITEM: TIMESTEP
54
abc
def
ghi
jkl
ITEM: TIMESTEP
55
horse
cat
dog
ITEM: TIMESTEP
56
tree
ITEM: TIMESTEP
57
house
school
...

file2.txt

150
68
201
202
...

Combine them to get:

ITEM: TIMESTEP
150
abc
def
ghi
jkl
ITEM: TIMESTEP
68
horse
cat
dog
ITEM: TIMESTEP
201
tree
ITEM: TIMESTEP
202
house
school
...

Thank you!

Upvotes: 0

Views: 76

Answers (2)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed -e '/TIMESTEP/{n;R file2' -e 'd}' file1

After encountering a line containing TIMESTEP print and then fetch the next line, read/print a line from file2 and then delete the current line from file1.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203209

$ awk '
    NR==FNR { vals[NR]=$0; next }
    found { $0=vals[++cnt]; found=0 }
    /TIMESTEP/ { found=1 }
    { print }
' file2 file1
ITEM: TIMESTEP
150
abc
def
ghi
jkl
ITEM: TIMESTEP
68
horse
cat
dog
ITEM: TIMESTEP
201
tree
ITEM: TIMESTEP
202
house
school

Upvotes: 1

Related Questions