Copy files from one directory into an existing directory

前端 未结 7 1128
野趣味
野趣味 2020-12-07 08:11

In bash I need to do this:

  1. take all files in a directory

  2. copy them into an existing directory

How do I do this? I tried

相关标签:
7条回答
  • 2020-12-07 08:13

    Depending on some details you might need to do something like this:

    r=$(pwd)
    case "$TARG" in
        /*) p=$r;;
        *) p="";;
        esac
    cd "$SRC" && cp -r . "$p/$TARG"
    cd "$r"
    

    ... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.

    The extra fussing is to handle relative or absolute targets.

    (This doesn't rely on subtle semantics of the cp command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp and I don't know if they'll continue to be so in the future).

    0 讨论(0)
  • 2020-12-07 08:18
    cp -R t1/ t2
    

    The trailing slash on the source directory changes the semantics slightly, so it copies the contents but not the directory itself. It also avoids the problems with globbing and invisible files that Bertrand's answer has (copying t1/* misses invisible files, copying `t1/* t1/.*' copies t1/. and t1/.., which you don't want).

    0 讨论(0)
  • 2020-12-07 08:19

    For inside some directory, this will be use full as it copy all contents from "folder1" to new directory "folder2" inside some directory.

    $(pwd) will get path for current directory.

    Notice the dot (.) after folder1 to get all contents inside folder1

    cp -r $(pwd)/folder1/. $(pwd)/folder2
    
    0 讨论(0)
  • 2020-12-07 08:22

    If you want to copy something from one directory into the current directory, do this:

    cp dir1/* .
    

    This assumes you're not trying to copy hidden files.

    0 讨论(0)
  • 2020-12-07 08:23
    cp dir1/* dir2
    

    Or if you have directories inside dir1 that you'd want to copy as well

    cp -r dir1/* dir2
    
    0 讨论(0)
  • 2020-12-07 08:24

    What you want is:

    cp -R t1/. t2/
    

    The dot at the end tells it to copy the contents of the current directory, not the directory itself. This method also includes hidden files and folders.

    0 讨论(0)
提交回复
热议问题