-->

Bash while loop to compare two files and print lin

2019-08-05 19:03发布

问题:

I have file1:

A
B
C
D

I have file2:

B
C

I want to use a while read loop to go through both files compare them and print out the line number of file1 for any matching lines.

COUNT=0
while read line
do
    flag = 0
    while read line2
    do
    COUNT=$(( $COUNT + 1 ))
       if ( "$line" = "$line2" )
        then
            flag = 1
        fi
     done < file1
     if ( flag -eq 1 )
     then
         echo $COUNT > file3
     fi
done < file2

However I get an error: B command not found

Please could someone let me know where I have gone wrong. Thanks.

回答1:

There are quite a lot of errors in this code, but to answer the question, the reason you are getting B command not found is because........ we use [] rather than () in bash.

other errors include:

COUNT=0
while read line
do
    flag=0         # no space between flag and =
    while read line2
    do
    COUNT=$(( $COUNT + 1 ))
    echo $line
    echo $line2

       if [ "_$line" = "_$line2" ]
        then
            flag=1         #no space again
        fi
     done < file1
     if [ $flag -eq 1 ]       # use $flag rather than flag
     then
         echo $COUNT > file3
     fi
done < file2


回答2:

You could also achieve what you are looking for using grep -c like this:

#!/bin/bash

# Clean file3 
>file3

while read line; do
    COUNT=$(grep -c "^$line$" file2)

    if [ $COUNT -ge 1 ]; then
        $COUNT >> file3
    fi
done < file1

grep -c prints the number of times an expression matches the file content.