0

I need to move files from a folder to a subfolder and this is a process that can be executed more than once, so the subfolder may not be empty.

Let's say the structure is as follows:

renatospaka@dell-w10home:~/devlpm$ ls -la
total 24
drwxr-xr-x  4 renatospaka renatospaka 4096 Sep  8 12:36 .
drwxr-xr-x 10 renatospaka renatospaka 4096 Sep  8 12:34 ..
drwxr-xr-x  2 renatospaka renatospaka 4096 Sep  8 12:36 api
-rw-r--r--  1 renatospaka renatospaka   10 Sep  8 12:36 file1.txt
-rw-r--r--  1 renatospaka renatospaka   10 Sep  8 12:36 file2.txt
drwxr-xr-x  2 renatospaka renatospaka 4096 Sep  8 12:34 new

There is this excellent question from which I extracted the following command: ls | grep -v new | xargs mv -t new. It really works and moves the content to the new folder. However, from the 2nd execution on, an error pops up because the destination folder is not empty and the process abends.

How to fix this problem? I've tried some flag combinations on xargs but all failed...

1 Answers1

1

mv complains because it does not get any arguments from xargs. Add -r to prevent xargs from executing if the input is empty:

   -r, --no-run-if-empty
          If the standard input does not contain any nonblanks, do not run the command.  Normally, the command is run once even if there is  no  in‐
          put.  This option is a GNU extension.

Also, you can control mv behavior when destination exists:

See man mv:

   -f, --force
          do not prompt before overwriting

-i, --interactive prompt before overwrite

-n, --no-clobber do not overwrite an existing file

So:

... |  xargs -r mv -f -t new

However, your command has serious problems when there are newlines or even spaces in your files. In general, do not parse output of ls.

pLumo
  • 26,947
  • I tested "... | xargs -r mv -f -t new" and even so it returns the following error:

    renatospaka@dell-w10home:~/devlpm$ ls | grep -v new | xargs -r mv -f -t new mv: cannot move 'api' to 'new/api': Directory not empty

    – Renato Spakauskas Sep 08 '20 at 16:55
  • Regarding "find . -maxdepth 1 -type f -exec mv -f -t new {} +", it generated a completely unexpected result, so I need to read more about this. BTW, I just changed ".maxdepth 1" to ".maxdepth 5" – Renato Spakauskas Sep 08 '20 at 16:57
  • I executed the command "find . -maxdepth 1 -type f -exec mv -f -t new {} +" but it doesn't work. It copies files but out of subfolders, at the end all files stay in "new" folder, no matter how the "maxdepth" is set. The structure I am copying is 4 degrees depth – Renato Spakauskas Sep 08 '20 at 22:56