Home General Chat
If you need urgent support, call 999 or go to your nearest A&E. To contact our Crisis Messenger (open 24/7) text THEMIX to 85258.
Read the community guidelines before posting ✨
Options

Linux programming help

Former MemberFormer Member Posts: 1,876,323 The Mix Honorary Guru
I need to write a program to do something like a 'vlookup' in excel. I want to match data from file2 based on two fields (where both match) in file1, and for matching lines, add the data from two of the fields from file2 to file1.

If anyone knows something in perl or awk that can do this, I'd be very happy :)

e.g.:
(match on field 1 and 2, and append column 4 and 5 to column 5 and 6)

file1
1 A X a
2 B Y b
3 C Z c
4 D X d
5 E Y e

file2
1 A Y b
2 C Z c
3 D X d
4 E Y e
5 E Z c

output
1 A X a Y b
2 B Y b
3 C Z c
4 D X d
5 E Y e Z c

Comments

  • Options
    Former MemberFormer Member Posts: 1,876,323 The Mix Honorary Guru
    This is more of a DB task really, but I guess it depends where your files are coming from

    Tell me more about your data.

    Will the first field always match 1:1 between the two files? If not is the the combination of the first two fields unique in both files?

    Are the files in the same order as each other?

    anyway, a simple script to produce the required results from the provided test data:
    #!/bin/sh
    
    if [ $# = 1 -a X$2 = X-h ]
    then
      echo usage: $0 file1 file2
      exit 0
    fi
    
    if [ $# != 2 ]
    then
      echo usage: $0 file1 file2
      exit 1
    fi
    
    [ -r $1 ] && exec 3< $1 || (echo can\'t read \"$1\"; false) || exit 3
    [ -r $2 ] && exec 4< $2 || (echo can\'t read \"$2\"; false) || exit 3
    
    
    while read -u3 first second rest
    do
      read -u4 first2 second2 rest2
      if [ X"$first" = X"$first2" -a X"$second" = X"$second2" ]
      then
        echo $first $second $rest $rest2
      else
        echo $first $second $rest
      fi
    done
    
    
    
  • Options
    Former MemberFormer Member Posts: 1,876,323 The Mix Honorary Guru
    So, was that what you needed, or do you need a more general version?
  • Options
    Former MemberFormer Member Posts: 1,876,323 The Mix Honorary Guru
    Hi guys

    Really sorry I didn't reply, I completely forgot about this thread! I got the job done using a version of your code, thanks a lot BG.
Sign In or Register to comment.