如何將所有檔案移動到子資料夾

如何將所有檔案移動到子資料夾

我需要將文件從資料夾移動到子資料夾,這是一個可以多次執行的過程,因此子資料夾可能不為空。

假設結構如下:

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

有這個優秀的問題我從中提取了以下命令:ls | grep -v new | xargs mv -t new。它確實有效並將內容移動到新的資料夾。但是,從第二次執行開始,會彈出錯誤,因為目標資料夾不為空,且進程異常終止。

如何解決這個問題?我嘗試了一些標誌組合,xargs但都失敗了...

答案1

mv抱怨是因為它沒有從 得到任何參數xargs。新增-r以防止xargs輸入為空時執行:

   -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.

此外,您可以控制mv目標存在時的行為:

man mv

   -f, --force
          do not prompt before overwriting

   -i, --interactive
          prompt before overwrite

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

所以:

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

但是,當檔案中存在換行符甚至空格時,您的命令會出現嚴重問題。一般來說,不解析輸出ls

相關內容