bash脚本复制文件夹中的所有文件

时间:2013-05-02 05:49:29

标签: bash

我正在编写一个shell脚本,如下所示:

for file in `ls`
do
  mkdir "$file"_folder
  cp $file "$file"_folder
done

我想要做的是为当前目录中的每个文件创建一个文件夹及其名称,然后将下划线文件夹作为名称,然后将该文件复制到其中。我的问题是文件名中包含空格。我怎么逃避他们? 有许多资源解释了如何为变量执行此操作,但是没有一个资源可以应用于我使用for循环来获取名称的情况。

3 个答案:

答案 0 :(得分:2)

不要在那里使用ls,使用shell globbing。 (一般来说,do not parse the output of ls。)

for file in *
do
  # only consider files, not directories
  if [ -f "$file" ] ; then
    new_dir="$file"_folder
    # create the directory
    if [ ! -d "$new_dir" ] ; then
      mkdir "$new_dir"
      if [ $? -ne 0 ] ; then
        # handle directory creation eror
      fi
    fi
    # possibly check for the copied file existence here
    # and deal with that appropriately (i.e. skip/error/copy anyway)
    cp "$file" "$new_dir"
  fi
done

答案 1 :(得分:1)

怎么样

find . -type f -exec mkdir {}_folder \; -exec cp {} {}_folder \;

它找到当前目录中的所有常规文件,创建文件夹(第一个-exec),然后将文件复制到新文件夹(第二个-exec)。

答案 2 :(得分:0)

do not parse ls正是因为这个原因

for file in *
do
  mkdir "${file}_folder"
  cp "$file" "${file}_folder"
done