shellunixshmv

Unix command to move multiple files at once to a target directory using parameterized filename?


I am trying to move specific file names all at once from one directory to other using single command line. I have captured the file names (not with full path) in a variable as shown below, it may have 100 to 1000 files names.

var="M1.txt,A2.dat,T300.log"

I tried following command its working mv /home/rrajendr/test1/{M1.txt,A2.dat,T300.log} /home/rrajendr/test2/

Same is not working if it's parameterized mv /home/rrajendr/test1/{"$var"} /home/rrajendr/test2/

Error mv: cannot stat ‘/home/rrajendr/test1/{M1.txt,A2.dat,T300.log}: No such file or directory

Its looking for a filename as exactly like this "{M1.txt,A2.dat,T300.log}" as is, its not interpreting as individual file name. Something is missing here, please let me know

I tried following option but didn't worked

mv /home/rrajendr/test1/echo $var -t /home/rrajendr/test2/

mv /home/rrajendr/test1/{$var}

mv /home/rrajendr/test1/{echo $var}

Reason I am looking this option

  1. My sourcepath is fixed and I dont want to define back to back with full qualifier for each file name because I have 100 of files.
  2. I don't want to switch to the file directory (cd /home/rrajendr/test1/) back and forth, as I am doing other operation like aws cli operation & snow cli commands.
  3. I have already stored 100 of file names in a variable as like this string var="M1.txt,A2.dat,T300.log"
  4. Don't want to do this other program like python etc, not looping in shell with for or while also not with xargs
  5. To initiate a multiple files moves using single command line

Solution

  • If you are creating the file list and know there are no funny characters in the list, I'd use eval:

    cmd="mv /home/rrajendr/test1/{$var} /home/rrajendr/test2"
    eval $cmd
    

    or even

    eval "mv /home/rrajendr/test1/{$var} /home/rrajendr/test2"
    

    Note that brace expansion is not (yet) a POSIX shell feature as of 2023. This will only work if your sh is bash or zsh or any other shell supporting brace expansion.

    I'd say that the proper way to do this, with much less opportunities to break, is to loop or use xargs. Why do you want to avoid that? Moving files is never a bottle neck.