Search code examples
bashstring-matching

Write to output file if code from file 1 never matches code from file 2


I need your help: I have two files and I need to match the lines of the file 1 with the lines of file 2 based on the first two columns (a b) in order to create some output file. Both files have the same structure but not the same content. I wrote a script and it works fine. But I have an additional problem: There are some cases where the code of file 1 (a b) never matches the code of file 2. Is there an option to refer to these cases as well? Sorry, I'm a complete beginner...

Here is how my code looks like:

#!/bin/bash
while read file1
do
    file1_line=( ${file1_lines[$counter_file1]} )
    file1_a=${file1_line[0]}  
    file1_b=${file1_line[1]}
    while read line_file2
    do
        file2_line=( ${file2_lines[$counter_file2]} )
        file2_a=${file2_line[0]}   
        file2_b=${file2_line[1]}

            if ["file1_a" == "file2_a"] && ["file1_b" == "file2_b"]
            then
                echo "TRUE"
            else
                counter_file2=[counter_file2+1]
            fi
    done < $file2
    counter_file2=0
    counter_file1=$[counter_file1+1]
 done

Solution

  • There are some cases where the code of file 1 (a b) never matches the code of file 2. Is there an option to refer to these cases as well?

    You can set a status flag inside your inner while loop to track if the line found a match or not. Outside of the inner loop, you can handle that special case.

    I haven't tested it, but something like this should work:

    #!/bin/bash
    while read file1
    do
        file1_line=( ${file1_lines[$counter_file1]} )
        file1_a=${file1_line[0]}  
        file1_b=${file1_line[1]}
    
        had_match=0
        while read line_file2
        do
            file2_line=( ${file2_lines[$counter_file2]} )
            file2_a=${file2_line[0]}   
            file2_b=${file2_line[1]}
    
                if ["file1_a" == "file2_a"] && ["file1_b" == "file2_b"]
                then
                    had_match=1
                    echo "TRUE"
                else
                    counter_file2=[counter_file2+1]
                fi
        done < $file2
    
        if (( had_match == 0 )); then
            # Do something special here
        fi
    
        counter_file2=0
        counter_file1=$[counter_file1+1]
     done