모든 파일을 하위 폴더로 이동하는 방법

모든 파일을 하위 폴더로 이동하는 방법

폴더에서 하위 폴더로 파일을 이동해야 하는데 이 프로세스는 두 번 이상 실행될 수 있으므로 하위 폴더가 비어 있지 않을 수 있습니다.

구조가 다음과 같다고 가정해 보겠습니다.

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. 실제로 작동하고 콘텐츠를새로운폴더. 그런데 2번째 실행부터 대상 폴더가 비어 있지 않고 프로세스가 이상 종료되어 오류가 발생합니다.

이 문제를 해결하는 방법은 무엇입니까? 몇 가지 플래그 조합을 시도했지만 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.

관련 정보