简体   繁体   中英

Comparing two different files

say I have two data files that could look like this.

A dog 3
A cat 1
A mouse 4
A chicken 4

and

B tiger 2
B chicken 1
B dog 3
B wolf 2

How would I be able to look at only the animals that are common in both files? Ideally, I would like the output to look something like

dog 3 3
chicken 4 1

But even outputting just the ones along with its value that are common in both files is good enough for me. Thanks.

这种单线应该做的:

awk 'NR==FNR{a[$2]=$2 FS $3;next}a[$2]{print a[$2],$3}' f1 f2 

@Kent has done some serious one line magic. Anyway, I did a shell script you could try. Simply run ./script[file1] [file2]

#!/bin/bash

# Read input
words1=$(cat $1 | sed -r "s/.*\ (.*)\ .*/\1/")
val1=$(cat $1 | sed -r "s/.*\ .*\ (.*)/\1/")
words2=$(cat $2 | sed -r "s/.*\ (.*)\ .*/\1/")
val2=$(cat $2 | sed -r "s/.*\ .*\ (.*)/\1/")

# Convert to array 
words1=($words1)
val1=($val1)
words2=($words2)
val2=($val2)

# Iterate and print result
for i in "${!words1[@]}"; do
    for j in "${!words2[@]}"; do
        if [ ${words1[i]} == ${words2[j]} ]; then
            echo "${words1[i]} ${val1[i]} ${val2[j]}"
            break
        fi
    done
done

exit 0

I'm not sure why this is a linux/unix question. It looks like what you need is a simple program that you'll need to write, as this isn't a basic compare-two-files issue that would be generally covered by applications like Beyond Compare.

Let's assume these files are basic text files that contain one record per line with space-delimited values. (Use space as the delimiter is dangerous, but that's what you have above). You'll need to read in each file, storing both files as [iterable collection], and have each object either be a string that you act on in each run of a loop, or that you break into pieces as you build from the file. You'll need to compare [linepart 1] from the first file to each [linepart 1] in the second file, and whenever you find a match, break and output [linepart 1] [A.linepart 2] [B.linepart 2].

I can't think of any existing program that would do this for you, but it's fairly simple (assuming you think file IO is simple) to handle with Java, C#, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM