使用嵌套循环读取和比较文件时出现问题

使用嵌套循环读取和比较文件时出现问题
while read newfile <&3; do   
 if [[ ! $newfile =~ [^[:space:]] ]] ; then  #empty line exception
    continue
 fi   
 #
 while read oldfile <&3; do   
 if [[ ! $oldfile =~ [^[:space:]] ]] ; then  #empty line exception
    continue
 fi   
    echo Comparing "$newfile" with "$oldfile"
    #
    if diff "$newfile" "$oldfile" >/dev/null ; then
      echo The files compared are the same. No changes were made.
    else
        echo The files compared are different.
    fi    
 done 3</infanass/dev/admin/oldfiles.txt
done 3</infanass/dev/admin/newfiles.txt

我认为这是执行嵌套循环的正确方法..但它不太正常工作。

答案1

您不必像那样使用文件描述符 3。

while read newfile do   
    if [[ ! $newfile =~ [^[:space:]] ]] ; then  #empty line exception
       continue
    fi   

    while read oldfile ; do   
       if [[ ! $oldfile =~ [^[:space:]] ]] ; then  #empty line exception
          continue
       fi   
       echo Comparing "$newfile" with "$oldfile"

       # diff -q doesn't bother generating a diff.
       # It just tells you whether or not the files match.
       if diff -q "$newfile" "$oldfile" >/dev/null ; then
         echo The files compared are the same. No changes were made.
       else
           echo The files compared are different.
       fi    
    done < /infanass/dev/admin/oldfiles.txt
done < /infanass/dev/admin/newfiles.txt

假设空行是只包含空格的行,则空行异常代码可能会匹配非空行。这将匹配仅包含空格的行(删除\s*以使其仅匹配完全空的行):

if [[ ! $newfile =~ ^\s*$ ]] ; then  #empty line exception

相关内容