问题
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=FileBThis creates an awk variable
fwhich 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 themsed '2~2d' fileAprints the odd lines offileA(by deleting the even lines)sed '1~2d' fileAprints the even lines offileAsed '1~2d' fileBprints the even lines offileB
回答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