Combining two files by inserting even lines of one file after even lines of other file

社会主义新天地 提交于 2019-12-12 23:08:04

问题


I would like to know a way to combine two files efficiently. I wanted to concatenate only even lines of FileB after even lines of FileA. I think it can be done easily with sed or awk. Any help is appreciated.

FileA:

A1
A2
A3
A4
A5
A6
.
.

FileB:

B1
B2
B3
B4
B5
B6
.
.

Output:

A1
A2
B2
A3
A4
B4
A5
.

回答1:


Here is an approach that avoids storing one of the files in memory:

awk -v f=FileB '{print} NR%2==0 {getline<f; getline<f; print}' FileA

How it works:

  • -v f=FileB

    This creates an awk variable f which contains the name of FileB.

  • {print}

    This prints every line read from FileA.

  • NR%2==0 {getline<f; getline<f; print}

    If we are on an even line, meaning NR%2==0, then we read two lines from FileB and print the second one.

Sample output:

$ awk -v f=FileB '{print} NR%2 == 0{getline<f; getline <f; print}' FileA
A1
A2
B2
A3
A4
B4
A5
A6
B6

More cryptic version

Awk allows prints to be performed with cryptic shorthand notations:

awk -v f=FileB '1; NR%2{next} {getline<f; getline <f} 1' FileA

Here, 1 is a condition which evaluates to true. Since no action is specified, the default action is performed which is to print the line.




回答2:


awk to the rescue!

awk 'NR==FNR {b[NR]=$0; next} 1; !(FNR%2){print b[FNR]}' fileB fileA

if files are large, you can cut the array size by only storing the printed lines of fileB.




回答3:


You can combine paste, sed and process substitution:

$ paste -d '\n' <(sed '2~2d' fileA) <(sed '1~2d' fileA) <(sed '1~2d' fileB)
A1
A2
B2
A3
A4
B4
A5
A6
B6

Explained:

  • paste -d '\n' pastes the files line by line, delimited by newlines, effectively interleaving them
  • sed '2~2d' fileA prints the odd lines of fileA (by deleting the even lines)
  • sed '1~2d' fileA prints the even lines of fileA
  • sed '1~2d' fileB prints the even lines of fileB



回答4:


This might work for you (GNU sed);

sed '1~2d' fileB | sed '2~2R /dev/stdin' fileA

Filter fileB on even numbered lines and pass the resulting file via a pipe to a second invocation of sed that appends these lines to only the even numbered lines in fileA.



来源:https://stackoverflow.com/questions/43859055/combining-two-files-by-inserting-even-lines-of-one-file-after-even-lines-of-othe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!