Merge files based on columns

011111123444 1234 1 20000 
011111123444 1235 1 30000
011111123446 1234 3 40000
011111123447 1234 4 50000
011111123448 1234 3 50000 

File2:

011111123444,Rsttponrfgtrgtrkrfrgtrgrer
011111123446,Rsttponrfgtrgtr 
011111123447,Rsttponrfgtrguii
011111123448,Rsttponrfgtrgtjiiu

I have 2 files : File1 and File2. File1 is a fixed length file. File 2 is comma delimiter file
I want to join both files based on column 1 and append it in postion 17- 41(Max 25) on File1.
Note: If the length of column 2 of file 2 is more than 25 then trim it. Also in the output file and file 1 has one space in the begining
of each line.

Desired Output:

011111123444 Rsttponrfgtrgtrkrfrgtrgre 1234 1 20000 
011111123444 Rsttponrfgtrgtrkrfrgtrgre 1235 1 30000
011111123446 Rsttponrfgtrgtr 1234 3 20000
011111123447 Rsttponrfgtrguii 1234 4 50000
011111123448 Rsttponrfgtrgtjiiu 1234 3 50000

Can anyone please help? The input and output file postion got changed while posting , please see the attached file.

I have attached the sample file

awk '
        NR == FNR {
                n = split ( $0, R, "," )
                A[R[1]] = R[n]
                next
        }
        $1 in A {
                printf ( " %-14s %-29s %s\n", $1, A[$1], substr($0,47) )
        }
' file2 file1

Join command is useful and the standard answer you will get but depending on the type of join one or both files must be sorted.

Often when I want to do this one file is changing constantly and huge, the other is relatively small and static or rarely changed. In that case, I usually read the smaller file into an associative array and match that way.

I've done this in both Bash and AWK (AWK is faster): For example in an AWK BEGIN block:

BEGIN { while (getline < "'"$indexFile"'" ) { split($0,myIndex,","); indexArr[imyIndex[1]]=myIndex[2] }
                     close("'"$indexFile"'") }

Read up on associative arrays as they are very powerful features of high level languages.

Mike

PS. I am just a Padawan compared to maser Yoda. I passed a Bash variable, Yoda did not. NR=FNR with two files indeed . . . :smiley:

Thanks , i made minor change and Its working fine.