将一个文件的每一行分别添加到另一个文件的每四行

Add each line of a file to every fourth line of another file respectively

我是 bash 的新手,我真的搞不懂这个问题。所以我有两个文件看起来像:

文件 1:

Jack
Peter
John
...

文件 2:

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

从文件 2 的第一行开始,每第四行我需要在文件 1 中添加相应的行,并使用“-”作为分隔符。结果应如下所示:

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

至此我已经确认文件2的行数恰好是文件1的四倍,请问如何得到上面的结果呢?感谢任何帮助。谢谢!

有两个 GNU sed:

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

输出:

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

来自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.

$ 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", [=10=], name; next} 1' file2
New York-Jack
Houston
Boston
Chicago
Los Angeles-Peter
San Diego
Dallas
San Jose
Phoenix-John

这可能适合您 (GNU sed):

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

在第一行,将 file1 放入保留 space。

对于第一行和每第四行,追加保留 space,将第一个换行符替换为 - 并仅打印第一行。

然后删除第一行,用结果覆盖保持 space 并删除当前行。

$ awk 'NR==FNR{a[NR]=[=10=]; next} {print [=10=] (FNR%4==1 ? "-" a[++c] : "")}' file1 file2
New York-Jack
Houston
Boston
Chicago
Los Angeles-Peter
San Diego
Dallas
San Jose
Phoenix-John

另一种方法

$ paste -d'[=10=]' file2 <(sed 's/^/-/;G;G;G' file1)

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

三个 space 第一个文件和前缀为 -,粘贴两个文件,不带分隔符。