파일 확장자를 기준으로 파일을 정렬하고 디렉터리로 이동합니다.

파일 확장자를 기준으로 파일을 정렬하고 디렉터리로 이동합니다.

파일의 모든 다양한 유형의 확장명을 허용하고 해당 확장명에서 디렉토리를 생성하는 스크립트가 있습니다.

하지만 3가지 확장 유형에 대한 디렉토리만 생성하면 됩니다. JPG/JPEG, DOC/DOCX 및 기타 유형 확장자가 "기타"인 디렉토리 1개.

이것은 지금까지 내 스크립트입니다.

#!/bin/bash
exts=$(ls | sed 's/^.*\.//' | sort -u)
for ext in $exts; do
  mkdir $ext
  mv -v *.$ext $ext/
done

답변1

그리고 zsh:

#! /bin/zsh -
# speed things up by making mv builtin
zmodload zsh/files

# associative array giving the destination directory for each
# type of file
typeset -A dst=(
  doc  doc
  docx doc
  jpg  jpeg 
  jpeg jpeg
)

# default for files with extensions not covered by $dst above or
# files without extension
default=miscellaneous

mkdir -p $dst $default || exit

for f (*(N.)) mv -i -- $f ${dst[$f:e:l]-$default}/
  • *(N.)숨겨지지 않은 모든 항목으로 확장정기적인.현재 디렉터리의 files()( Nullglob을 사용하므로 해당 파일이 없으면 빈 목록으로 확장됩니다).
  • $f:e:lf는 ile의 확장 이며 소문자 e로 변환됩니다 l(따라서 및 둘 다 로 FILE.DOCX이동 됩니다 .file.docxdoc
  • ${var-default}표준/Bourne 연산자로, 설정이 없는 default경우 까지 확장됩니다(여기서는 연관 배열 요소에 적용됨).$var

zsh의 내장 함수는 mv이 옵션(GNU 확장)을 지원하지 않지만 루프 대신 를 -v사용할 수 있습니다 .zmv

autoload zmv
zmv -v '*(#qN.)' '${dst[$f:e:l]-$default}/$f'

답변2

에서 다음과 같은 것을 시도해 볼 수 있습니다 bash.정규식 이진 연산자=~:

# create an array of "known" extensions
known_ext=(jpg jpeg doc docx)

# loop over the files
for f in *; do
  # if not a file keep looping
  [ ! -f "$f" ] && continue
  # if file has a known extension
  if [[ " ${known_ext[@]} " =~ " ${f##*.} " ]]; then
    # create the dir if not exists
    mkdir -p "${f##*.}" &&
    # and move the file to that dir
    mv -- "$f" "${f##*.}"
  else
    # else create dir miscellaneous if not exists
    mkdir -p miscellaneous &&
    # move the file
    mv -- "$f" miscellaneous
  fi
done

답변3

다음 명령을 실행합니다.

mkdir miscellaneous doc jpg
find . -maxdepth 1 -type f \( -name "*.doc" -o -name "*.docx" \) -exec mv -v {} doc/ \;
find . -maxdepth 1 -type f \( -name "*.jpg" -o -name "*.jpeg" \) -exec mv -v {} jpg/ \;
find . -maxdepth 1 -type f -exec mv -v {} miscellaneous/ \;

다음 테스트를 통해 원하는 방식으로 작동하는지 확인할 수 있습니다.

touch foo.mp3 foo.mp4 foo.doc foo.docx foo.jpg foo.jpeg foo.png foo

위 명령을 실행하고 tree파일이 어떻게 이동되는지 확인하십시오.

tree
.
├── doc
│   ├── foo.doc
│   └── foo.docx
├── jpg
│   ├── foo.jpeg
│   └── foo.jpg
└── miscellaneous
    ├── foo
    ├── foo.mp3
    ├── foo.mp4
    └── foo.png

3 directories, 8 files


관련 정보