-1

I have two text files that I would like to be read in as matrices. Matrix A (or text file A) is tab delimited and contains a latitude column, longitude column, and name column (among other things). Matrix B (or text file B) is tab delimited and contains a latitude column, and longitude column (among other things). I would like to read each of these in, assign names to the columns, loop through A's Latitude looking for matching ones in B, if there is a match, compare Longitude, if there is a match, write a new matrix C (text file C) that has lat, long, and name (with the other information from the column). I don't even know how to go about reading these in and assigning names to the column values. Is this possible?

  • 1
    please post sample input files and desired output. You'll be surprised how many different solutions exist. – karakfa Dec 08 '16 at 19:44

1 Answers1

1

If you want a pure Bash solution, then something along these lines could do it:

file_a=A
file_b=B
file_c=C

while read -r lat_a long_a name_a acol ; do
    while read -r lat_b long_b bcol ; do
        if [[ $lat_a == "$lat_b" && $long_a == "$long_b" ]] ; then
            printf '%s\t%s\t%s\t%s\t%s\n' \
                "$lat_a" "$long_a" "$name_a" "$acol" "$bcol"
        fi
    done <"$file_b"
done <"$file_a" >"$file_c"

That assumes one extra column in each of the files (acol in the first one and bcol in the second one). It would need to be adapted to handle whatever the real columns are.

The Bash code re-reads the entire second file for every line of the first file that it reads, so it will be very slow if the files are big.

A better alternative may be to use the join command. See Bash join command for examples (but note that the title is misleading: join is a standalone program that does not depend on Bash).

Community
  • 1
  • 1
pjh
  • 6,388
  • 2
  • 16
  • 17