2017-04-12 195 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