Home > Enterprise >  Add each line of a file to every fourth line of another file respectively
Add each line of a file to every fourth line of another file respectively

Time:01-09

I am quite new to bash and I cannot really figure out this problem. So I have two files which look like:

File 1:

Jack
Peter
John
...

File 2:

New York
Houston
Boston
Chicago
Los Angeles
San Diego
Dallas
San Jose
Phoenix
...

From the first line of file 2, for every fourth line I need to add the corresponding line in file 1 with a "-" as delimiter. The outcome should look like this:

New York-Jack
Houston
Boston
Chicago
Los Angeles-Peter
San Diego
Dallas
San Jose
Phoenix-John

So far I have confirmed that the number of lines in file 2 is exactly four times that in file 1. How should I get the outcome above? Appreciate any help. Thanks!

CodePudding user response:

With two GNU sed:

sed '1~4 R file1' file2 | sed '1~5{ N; s/\n/-/ }'

Output:

New York-Jack
Houston
Boston
Chicago
Los Angeles-Peter
San Diego
Dallas
San Jose
Phoenix-John

From man sed:

first~step: Match every step'th line starting with line first.

R filename: Append a line read from filename. Each invocation of the command reads a line from the file. This is a GNU extension.

CodePudding user response:

$ cat file1
Jack
Peter
John
$ cat file2
New York
Houston
Boston
Chicago
Los Angeles
San Diego
Dallas
San Jose
Phoenix
$ awk 'NR%4 == 1{getline name < "file1"; printf "%s-%s\n", $0, name; next} 1' file2
New York-Jack
Houston
Boston
Chicago
Los Angeles-Peter
San Diego
Dallas
San Jose
Phoenix-John

CodePudding user response:

This might work for you (GNU sed):

sed '1{x;s/^/cat file1/e;x};1~4{G;s/\n/-/;P;s/[^\n]*\n//;h;d}' file2

On the first line, slurp file1 into the hold space.

For the first and then every fourth line, append the hold space, replace the first newline by - and print the first line only.

Then remove the first line, over-write the hold space with the result and delete the current line.

  •  Tags:  
  • Related