如何使用bash脚本将所有* .html文件从一个文件夹复制到另一个文件夹?

时间:2017-04-12 13:30:39

标签: bash

我有以下文件夹结构:

..
 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 个答案:

答案 0 :(得分: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

不必再担心了。

为了扩展这个答案,我还使用了*.html glob,这基本上意味着:给我所有包含.html终止的文件

小心并记住 glob 不使用标准正则表达式集。

答案 1 :(得分:0)

试一试 -

find /home/Foo/folder_source -name "*.html" -exec cp {} /home/Foo/other_folder/folder_destination  \;
相关问题