2017-04-12 193 views
1

我有以下文件夾結構:如何使用bash腳本將所有* .html文件從一個文件夾複製到另一個文件夾?

.. 
documents 
    folder_destination // <- here I want to put *.html files 
    project 
     scripts 
      myScript.sh 
     folder_source 
      a.html 
      b.html 
      c.html 

我想寫在myScript.sh文件bash腳本, 將所有的* .html文件從folder_source複製到folder_destination。

myScript.sh代碼示例:

#!/bin/bash 

cd ../folder_source 
for f in *.html 
do 
    cp -v "$f" ../../folder_destination/"${f%.html}".html 
done 

但它不工作

+2

'CP文件/項目/ folder_source/* HTML文檔/ folder_destination /'? – 2017-04-12 13:32:22

+0

我可以使用相對路徑嗎? @Dex'ter – Dmitry

回答

4

爲什麼你甚至可以通過文件循環?

你可以簡單:

cp -v documents/project/folder_source/*.html documents/folder_destination/ 

如果要使用相對路徑,你可以從folder_source做到這一點:

cp -v *.html ../../folder_destination/ 

更多,如果你是比folder_source更低的水平,您可以按照上述相同的規則執行以下操作:

cp -v ../*.html ../../folder_destination/ 

更有甚者,如果你不想搞烏龍,只是創建兩個變量,說:

  • SOURCE_DIRECTORY
  • DESTINATION_DIRECTORY

和爲它們分配folder_sourcefolder_destination的絕對路徑。這樣,您可以簡單地:

#!/bin/bash 

SOURCE_DIRECTORY='/home/Foo/folder_source' 
DESTINATION_DIRECTORY='/home/Foo/other_folder/folder_destination' 

cp -v $SOURCE_DIRECTORY/*.html $DESTINATION_DIRECTORY 

無需再擔心了。


爲了擴展這個答案,我也用了*.htmlglob這基本上意味着:給我所有包含的.html終止文件。

小心並記住glob不使用標準正則表達式集。

+0

它向我顯示了一個錯誤:cd:../folder_destination:沒有這樣的文件或目錄@Dex'ter – Dmitry

+0

檢查編輯的完整解決方案:)在CentOS 7.3機器上測試。 – 2017-04-12 14:03:14

+0

我試過這種方式:cp -v ../folder_source/*.html ../../folder_destination但是得到一個錯誤:../folder_source/*。html沒有這樣的文件或目錄 – Dmitry

0

試試這個 -

find /home/Foo/folder_source -name "*.html" -exec cp {} /home/Foo/other_folder/folder_destination \; 
+0

我不能使用絕對路徑@VIPIN KUMAR – Dmitry

+0

我想使用與腳本文件夾相關的路徑 – Dmitry