The shell inserts a line every n lines

I have two files, and I'm trying to insert a line from file2 into file1 every four lines, starting at the beginning of file1. For example:

file1:

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10

file2:

50
43
21

I am trying to get:

50
line 1
line 2
line 3
line 4
43
line 5
line 6
line 7
line 8
21
line 9
line 10

The code I have is:

while read line
do
    sed '0~4 s/$/$line/g' < file1.txt > file2.txt
done < file1.txt

I get the following error:

sed: 1: "0~4 s/$/$line/g": invalid command code ~
+4
source share
5 answers

The following steps are for both files without loading one into an array in memory:

awk '(NR-1)%4==0{getline this<"file2";print this} 1' file1

This may be preferable if your actual is file2more than what you want to keep in mind.

This is interrupted as follows:

  • (NR-1)%4==0 - a condition that matches every fourth line starting at 0
  • getline this<"file2" - receives a line from the file "file2" and saves it in a variable this
  • print this - prints ... this.
  • 1 - " ", 1 ( awk)
+2

, awk:

awk 'FNR==NR{a[i++]=$0; next} !((FNR-1) % 4){print a[j++]} 1' file2 file1

50
line 1
line 2
line 3
line 4
43
line 5
line 6
line 7
line 8
21
line 9
line 10
  • i.e. file2 , 0.
  • , .. file1, , # 4 , file2 .
  • , 1, file1.
+2

(GNU sed):

sed -e 'Rfile1' -e 'Rfile1' -e 'Rfile1' -e 'Rfile1' file2

cat paste:

cat file1 | paste -d\\n file2 - - - -
+2

unix toolchain

$ paste file2 <(pr -4ats file1) | tr '\t' '\n'

50
line 1
line 2
line 3
line 4
43
line 5
line 6
line 7
line 8
21
line 9
line 10
+1

Here you can do it with pasteandtr

paste file2 <(paste - - - - <file1) | tr '\t' '\n'

It is assumed that you do not have actual tabs in your input files.

-1
source

All Articles