批处理文件检查文件是否存在于比较文本文件名称的文件夹中

时间:2013-10-09 09:25:35

标签: linux bash shell

我正在尝试编写批处理文件,该文件检查文本文件中存在的文件名是否存在于文件夹中。 我有一个名为PAN的文件夹,其中有一个名为PRAS_filelist.txt的文本文件,它存储了所有文件名。还有一个文件夹PRAS,其中存在我的所有文件。

我的要求是它应该扫描文件夹,最后,它应该在文件PRAS_PP_ERROR_LOG中填充错误消息。但是现在,如果因为我使用了退出而没有任何一个文件,它就会出现。

以下是代码

`rm -f ../SessLogs/PRAS_PP_ERROR_LOG`
for i in `cat ./PAN/PRAS_filelist.txt`
do
    file_name=$i
    if [ -e ./PAN/PRAS/"$file_name"_* ]
    then
        if [ -s ./PAN/PRAS/"$file_name"_* ]
        then
            a=`sed -n '1p' ./PAN/PRAS/"$file_name"_*|cut -d'|' -f1`
            b=`sed -n '$p' ./PAN/PRAS/"$file_name"_*|cut -d'|' -f1`
            if [ "$a" == "H" ] && [ "$b" == "T" ]
            then
                trailer_record=`sed -n '$p' ./PAN/PRAS/"$file_name"_*|cut -d'|' -f2`
                record_count=`wc -l ./PAN/PRAS/"$file_name"_*|cut -d' ' -f1`
                r_c=`expr $record_count - 1`
                if [ $trailer_record -eq $r_c ]
                then
                    `cp ./PAN/PRAS/"$file_name"_* ./PAN/PRAS/STANDARDIZE/"$file_name"`
                    `sed -i '$d' ./PAN/PRAS/STANDARDIZE/"$file_name"`
                else 
                    echo "ERROR in file $file_name: Count of records is $r_c and trailer is $trailer_record">../SessLogs/PRAS_PP_ERROR_LOG  
                fi  
            else
                echo "ERROR in file $file_name: header or trailer is missing">../SessLogs/PRAS_PP_ERROR_LOG
                exit 1 
            fi 
        else
            echo "ERROR in file $file_name: empty file">../SessLogs/PRAS_PP_ERROR_LOG
            exit 1
        fi
    else
        echo "ERROR: $file_name doesnot exist">../SessLogs/PRAS_PP_ERROR_LOG
        exit 1
    fi
done

1 个答案:

答案 0 :(得分:0)

稍微重构一下代码:

有一件奇怪的事情是你声称有一个文件名列表,但是在检查文件存在之前你会附加一个下划线。实际的文件名实际上是否有下划线?

#!/bin/bash
shopt -s nullglob

logfile=../SessLogs/PRAS_PP_ERROR_LOG
rm -f $logfile

while read file_name; do
    files=( ./PAN/PRAS/${file_name}_* )
    if (( ${#files[@]} == 0 )); then
        echo "ERROR: no files named ${file_name}_*"
        continue
    elif (( ${#files[@]} > 1 )); then
        echo "ERROR: multiple files named ${file_name}_*"
        continue
    fi

    f=${files[0]}

    if [[ ! -s $f ]]; then
        echo "ERROR in file $f: empty file"
        continue
    fi

    a=$(sed    '1q' "$f" | cut -d'|' -f1)
    b=$(sed -n '$p' "$f" | cut -d'|' -f1)

    if [[ "$a" != "H" || "$b" != "T" ]]; then
        echo "ERROR in file $f: header or trailer is missing"
        continue
    fi 

    trailer_record=$(sed -n '$p' "$f" | cut -d'|' -f2)
    r_c=$(( $(wc -l < "$f") - 1 ))

    if (( trailer_record == r_c )); then
        sed '$d' "$f" > ./PAN/PRAS/STANDARDIZE/"$file_name"
    else 
        echo "ERROR in file $f: Count of records is $r_c and trailer is $trailer_record"
    fi  

done < ./PAN/PRAS_filelist.txt | tee $logfile