简体   繁体   中英

Merge two files by line numbers using awk or sed

I have two files, say FileA and FileB. FileA has n lines and FileB has 5n lines. I want to merge these two files into a new file FileC such that every 5th line in FileB is replaced by a line from FileA.

Example

FileA : 0\\n, 1\\n

FileB: A\\n B\\n C\\n D\\n E\\n F\\n G\\n H\\n I\\n J\\n

FileC: 0\\n B\\n C\\n D\\n E\\n 1\\n G\\n H\\n I\\n J\\n

(\\n is newline)

I know how to do this using a loop in shell but I was hoping to learn a cleaner way of doing this using perhaps awk or sed. I found many solutions of processing two files using awk but they are mostly based on field comparisons and not line numbers. I apologize if this question is a repeat, if so, please point me to a similar question with answers.

awk '{if(NR%5==1) { getline line < "FILEA"; print line; } else { print $0; }}' FILEB

如果要将文件名用作参数,也可以尝试以下操作:

awk 'NR!=FNR{exit} {if(NR%5==1) { getline line < ARGV[2]; print line; } else { print $0; }}' FILEB FILEA
awk 'NR!=FNR{exit}NR%5==1{getline <ARGV[2]}{print}' FileB FileA

Note that filenames are entered in the opposite order: largefile smallfile.

This also gracefully handles the case that FileA is shorter than 1/5th FileB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM