簡體   English   中英

檢查UNIX目錄中是否存在兩個文件

[英]Check that two file exists in UNIX Directory

早上好,

我試圖編寫一個korn shell腳本,以查看包含文件負載的目錄內部,並檢查每個文件的末尾是否也帶有.orig。

例如,如果目錄中的文件名為“ mercury_1”,則還必須有一個名為“ mercury_1.orig”的文件

如果沒有,則需要將mercury_1文件移動到另一個位置。 但是,如果.orig文件存在,則不執行任何操作,然后移至下一個文件。

我敢肯定這確實很簡單,但是我在編寫Linux腳本方面經驗不足,將不勝感激!

這是一個ksh小片段,用於檢查當前目錄中是否存在文件

fname=mercury_1
if [ -f $fname ]
then
  echo "file exists"
else
  echo "file doesn't exit"
fi

編輯:

具有上述功能的更新腳本

#/usr/bin/ksh
if [ ! $# -eq 1 ]
then
    echo "provide dir"
    exit  
fi

dir=$1

cd $dir

#process file names not ending with orig
for fname in `ls | grep -v ".orig$"`
do
  echo processing file $fname
  if [ -d $fname ]  #skip directory
  then
    continue
  fi

  if [ -f "$fname.orig" ] #if equiv. orig file present 
  then
    echo "file exist"
    continue
  else
    echo "moving"       
    mv $fname /tmp
  fi

 done

希望它的幫助!

您可以使用以下腳本

script.sh:

#!/bin/sh

if [ ! $# -eq 2 ]; then
    echo "error";
    exit;
fi

for File in $1/*
do
    Tfile=${File%%.*}
    if [ ! -f $Tfile.orig ]; then
        echo "$File"
        mv $File $2/
    fi
done

用法:

./script.sh <search directory>  <destination dir if file not present>

在這里,對於每個帶擴展名的文件,檢查是否存在“ * .orig”,如果不存在,則將文件移動到其他目錄,否則什么也不做。

擴展名被刪除,因為您不想對*.orig文件重復相同的步驟。

我在OSX上進行了測試(基本上mv與linux的差別不大)。 我的測試目錄是zbar,目標是/ tmp目錄

 #!/bin/bash
 FILES=zbar
 cd $FILES
 array=$(ls -p |grep -v "/")  # we search for file without extension so put them in array and ignore directory
 echo $array
 for f in $array #loop in array and find .orig file 
 do
 #echo $f
 if [ -e "$f.orig" ]
   then
   echo "found $f.orig"
 else
     mv -f "$f" "/tmp"
   fi
 done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM