How to copy or move multiple files with same extension?

你离开我真会死。 提交于 2020-01-15 09:18:07

问题


So I am trying to move a bunch of files with similar extensions from /home/ to /root/

Code I tried is

file copy /home/*.abc.xyz /root/

Also tried

set infile [glob -nocomplain /home/*.abc.xyz ]
if { [llength $infile] > 0 } { 
    file copy $infile /root/
}

No success.


回答1:


Your two attempts fail for different reasons:

  1. There is no wildcard expansion in arguments to file copy, or any Tcl command, for that matter: file copy /home/*.abc.xyz /root/. This will look for a single source with a literal * in its filename.

  2. glob -nocomplain /home/*.abc.xyz is ok to collect the sources, but glob returns a list of sources. file copy requires each source to passed as a separate argument, not a single one. To expand a single collection value of source files into a multiple separate arguments, use the Tcl expansion operator {*}

Therefore:

set infiles [glob -nocomplain *.tcl]
if {[llength $infiles]} {
   file copy {*}$infiles /tmp/tgt/
}



回答2:


For a 1-line answer:

file copy {*}[glob /home/*.abc.xyz] /root/.



回答3:


The file copy (and file rename) commands have two forms (hence the reference to the manual page in the comment). The first form copies a single file to a new target. The second form copies all the file name arguments to a new directory and this form of the command insists that the directory name be the last argument and you may have an arbitrary number of source file names preceding. Also, file copy does not do glob expansion on its arguments, so as you rightly surmised, you also need to use the glob command to obtain a list of the files to copy. The problem is that the glob command returns a list of file names and you passed that list as a single argument, i.e.

file copy $infile /root/

passes the list as a single argument and so the file copy command thinks it is dealing with the first form and attempts to find a file whose name matches that of the entire list. This file probably doesn't exist. Placing the error message in your question would have helped us to know for sure.

So what you want to do is take the list of files contained in the infile variable and expand it into separate argument words. Since this is a common situation, Tcl has some syntax to help (assuming you are not using some ancient version of Tcl). Try using the command:

file copy {*}$infile /root/

in place of your first attempt and see if that helps the situation.



来源:https://stackoverflow.com/questions/51409347/how-to-copy-or-move-multiple-files-with-same-extension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!