Roy Aja Roy Aja
Roy Aja Roy Aja

Reputation: 33

combine two files side by side with special condition

sorry for the bad title folks , i dont how how to describe except with example.

so here we go , i have to files like these :

file 1 :

left1
left2
left3

file 2

right1
right2
right3

expected output :

left1 right1
right2 left2
left3 right3

i know we can use paste command to combine those two files side by side , but i dont know ow to make it like output above .

root@s132496:~# paste -d ' ' file1 file2
left1 right1
left2 right2
left3 right3

i read man paste but still cant figure out yet how to. please help me solve this , been working since morning with no luck.

thank you before folks!

Upvotes: 1

Views: 99

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133458

Since you haven't told us that how many fields do you have in your Input_files and do we need to do interchange always 2nd line's fields etc things, so posting this by seeing your samples only.

paste -d" " file1 file2 | awk 'FNR==2{$0=$2 OFS $1} 1'

Upvotes: 3

user000001
user000001

Reputation: 33317

With awk you could do something like this:

awk 'NR==FNR{a[FNR]=$0;next}FNR%2{print $0, a[FNR];next}{print a[FNR], $0}' file1 file2

Expanded:

awk 'NR == FNR {        # For first input file (file1)
       a[FNR] = $0      # Store the current line in a new entry in array a
       next             # and skip to the next record
     }
     FNR % 2 {          # If the line number is odd
       print $0, a[FNR] # print in one order
       next             # and skip to the next record
     }
     {                  # for the rest lines (file2 even lines)
       print a[FNR], $0 # print in opposite order
     }' file1 file2

The assumption here is that file1 is small enough to fit in memory, otherwise use cut and pipe to awk, but that will only work if you don't have spaces in the lines of file1 and file2.

Upvotes: 2

Related Questions