Bash while loop to compare two files and print line number

▼魔方 西西 提交于 2019-12-24 14:24:57

问题


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.



来源:https://stackoverflow.com/questions/29156902/bash-while-loop-to-compare-two-files-and-print-line-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!