linux - 循环遍历一个目录并检查它是否存在于另一个目录中

标签 linux bash loops if-statement redhat

我在目录 A 中有一个包含 20000 个文件的文件夹和另一个文件夹 另一个目录 B 中有 15000 个文件,我可以循环遍历一个目录 使用:

DIR='/home/oracle/test/forms1/'

for FILE in "$DIR"*.mp
do
   filedate=$( ls -l --time-style=+"date %d-%m-%Y_%H-%M" *.fmx |awk  '{print $8 $7}')
    echo "file New Name $FILE$filedate "
#    echo "file New Name $FILE is copied "
done

我需要循环遍历目录A中的所有文件并检查它们是否 存在于目录B中

我尝试了以下方法,但似乎不起作用:

testdir='/home/oracle/ideatest/test/'
livedir='/home/oracle/ideatest/live/'

for FILET in "$testdir" #
do
    testfile=$(ls $FILET)
    echo $testfile

    for FILEL in "$livedir"
    do
        livefile=$(ls $FILEL)

        if [ "$testfile" = "$livefile" ]
        then
            echo "$testfile"
            echo "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
        else
            echo "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn"
        fi
    done
done

i'am trying to fix the result of years of bad version control we have that very oly script that send a form to live enviorment but every time it's compiled and sent the live version is named like (testform.fmx) but in test dir there is like 10 files named like (testform.fmx01-12-2018) (testform.fmx12-12-2017)(testform.fmx04-05-2016) as a reuslt we lost track of the last source sent to live enviroment that's why i created this

filedate=$( ls -l --time-style=+"date %d-%m-%Y_%H-%M" *.fmx |awk 
'{print $8 $7}')
echo "file New Name $FILE$filedate " 

为了匹配格式并循环每个目录并使用 ls 我可以通过匹配大小以及年份和月份来找到最后一个版本

最佳答案

您基本上可以使用diff命令来比较文件和目录。 比较文件夹A文件夹B 我认为你真的不需要为此使用循环..

如果您确实想使用循环,您可能还需要比较文件。

#!/bin/bash
DIR1="/home/A"
DIR2="/home/B"
CmpCmn=/usr/bin/cmp
DiffCmn=/usr/bin/diff

for file1 in $DIR1/*; do #Get the files under DIR1 one by one
        filex=$(basename $file1) #Get only the name ofthe ile
        echo "searching for $filex"
         $DiffCmn $filex $DIR2  #Check whether the file is under DIR2 or not
        if [ $? -ne 0 ]
        then
                echo " No file with $filex name under $DIR2 folder"
        else
                echo " $filex exists under $DIR2" 
                $CmpCmn  $file1 $DIR2/$filex  #Compare if the files are exactly same
                if [ $? -ne 0 ]
                then
                         echo " $filex is not same"
                 else
                         echo " $filex is the same"
                 fi
fi
        done

关于linux - 循环遍历一个目录并检查它是否存在于另一个目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52603713/

相关文章:

bash - shell 脚本 : Iterating over array of json

Python 数组操作,pi*[n+1]^2 - pi*[n]^2

json - React中嵌套JSON解析

linux - 在 Qemu 上运行的 RISC-V Linux

linux - 在 Linux 中将日期 append 到文件名

linux - 逐行读取模式之间的内容,然后以限定格式打印

bash - 修复小型 Bash 程序中的 POSIX sh 警告

linux - 在两台 Linux 计算机之间发送队列时如何更改消息大小?

mysql - 使用 MDB 工具从 Access 更新 MySQL 的 bash 脚本

c - 我想搜索字符串 s 中字符串 str 的元素,但是当我尝试搜索字符串 s 中的任何内容(例如 str[1])时,它返回 0