2014-09-03 101 views
0

我的代碼如下,應該遞歸地查找包含doc/docx文件的文件夾,並僅存檔它們的路徑。當在焦油中找到空時。 tar怯懦地拒絕創建一個空檔案。我使用-maxdepth 1來避免它,但不確定這是否是正確的解決方案。另一個問題是沒有按預期工作。如果不是存在,則測試將被忽略。有什麼建議麼? 也隨時提出一些代碼優化焦油和遞歸歸檔

for D in $(find . ! -newermt $date1 -ipath "*test*" -or -ipath "*notest*" -iregex ".*\.\(doc\|docx\)" -printf "%h\n" | sort -u) 
    do : 
    cd $D && tar --no-recursion --ignore-failed-read -czf archive.tar.zip $(find . -maxdepth 1 -iname "*.doc" -or -iname "*.docx") --remove-files 
    cd ~ 
done 

Test 
    |____ test 
    |  |___ subtest ___ 1.doc 
    |     |___ 2.doc 
    |     |___ 3.pdf 
    |____ notest ___ 1.doc 
       |___ 2.docx 

預計

Test 
    |___ test 
    |  |___ subtest ___ archive.tar.zip (contains docs) 
    |     |___ 3.pdf 
    |___ notest ___ archive.tar.zip (contains docs) 
+0

注意'.zip'表示存檔的特定類型,你可以用[拉鍊](HTTP操作:// WWW。 freebsd.org/cgi/man.cgi?query=zip&manpath=FreeBSD+Ports+9.2-RELEASE)和[unzip](http://www.freebsd.org/cgi/man.cgi?query=unzip&manpath=FreeBSD+Ports + 9.2-RELEASE)。對於gzipped tar,通常在'.tar.gz'中結束文件名。 – ghoti 2014-09-03 13:22:14

+0

這是這個想法,因爲這是一個雲存儲,可以通過運行不同操作系統的不同工作站打開。所以不想用工具來限制用戶。 – Odin 2014-09-04 08:49:52

+0

更改文件的名稱不會更改文件的格式。如果你想創建一個zip壓縮文件,你必須使用一個可以做到的工具。焦油可能不是那種工具。如果你希望在幾乎所有的類Unix系統中都能以相同的方式工作,那麼'.tar.gz'可能就是要走的路。如果你想兼容Windows,ZIP可能是更好的選擇。無論哪種方式,您都需要適合這項工作的工具。 – ghoti 2014-09-04 19:39:14

回答

1

嘗試了下:

arch="archive.tar.gz" 
while read -r -d $'\0' dir 
do 
    (cd "$dir" && find . -maxdepth 1 -iregex '.*\.docx?' -print0 | tar --null -czf "$arch" -T - --remove-files) 
    #alternatively 
    #(cd "$dir" && shopt -s nocaseglob nullglob && tar --no-recursion -czf "$arch" *.doc *.docx --remove-files) 
done < <(find . \(-ipath '*/test/*' -o -ipath '*/notest/*' \) -iregex '.*\.docx?' -printf '%h\0' | sort -zu) 

一些意見:

  • 替代-ipath與建築\(-ipath '*/test/*' -o -ipath '*/notest/*' \)
  • 正則表達式.*\.docx? - 必須整個文件名匹配,並且x?意味着零或一個x
  • 焦油可以從-T -
  • 標準輸入讀取文件列表
  • 使用空終止文件名(幫助如果路徑包含空格)
  • --null指示tar使用su CH空終止的文件名
  • (cd ... &&)在子shell運行,因此不需要cd
+0

我部分使用了你的建議,它給出了更好的結果。謝謝 – Odin 2014-09-04 08:48:21

+0

@Odin沒問題。 ANYWAY,對我來說,給出了你想要的 - 如果你有一些問題,編輯你的問題... – jm666 2014-09-04 12:25:37

+0

我怎樣才能使用'-iregex'和'-ipath'。例如'\(-ipath -iregex「。* \。\(test \ | notest \)\)」'? – Odin 2015-05-14 20:06:01