Bash 스크립트를 사용하여 파일을 폴더로 이동

Bash 스크립트를 사용하여 파일을 폴더로 이동

내 홈 디렉토리에는 FTP 서버에서 추출된 , , 및 기타 Apple-AP01파일 Apple-AP02Banana-AP05여러 개 있습니다 . 동일한 Chocolate-RS33홈 디렉토리에는 Fruit. 이러한 폴더 내에는 , 등의 하위 폴더 Sweet도 있습니다 .Apple-AP01Apple-AP02Chocolate-RS33

내 홈 디렉토리에서 스크립트를 실행하여 일단 스크립트를 갖게 되면 " " 키워드를 기반으로 Fruit 폴더에 넣은 다음 해당 폴더에 추가로 넣도록 Apple-AP01해야 합니다 . 의 경우 " " 키워드에 따라 폴더를 입력한 다음 폴더 내의 하위 폴더를 추가로 입력 해야 합니다 . 내 모든 파일에는 이것이 필요합니다. 누군가 작동하는 bash 스크립트를 작성할 수 있습니까?APApple-AP01Chocolate-RS33SweetRSChocolate-RS33Sweet

나는 노력했다

for f in *.
do
    name=`echo "$f"|sed 's/ -.*//'`
    letter=`echo "$name"|cut -c1`
    dir="DestinationDirectory/$letter/$name"
    mkdir -p "$dir"
    mv "$f" "$dir"
done

루프를 사용해야 할 것 같은데 forbash에서 어떻게 사용하는지 모르겠습니다.

답변1

여기에는 수행하려는 대부분의 작업이 포함되어야 합니다.

sortfood.sh

#!/bin/bash


# Puts files into subdirectories named after themselves in a directory.

# add more loops for more ID-criteria

for f in *AP*; do
    mkdir -p "./fruit/$f";
    mv -vn "$f" "./fruit/$f/";
done

for f in *RS*; do
    mkdir -p "./sweet/$f";
    mv -vn "$f" "./sweet/$f/";
done

답변2

귀하의 요구 사항을 충족하는지 확인하십시오.

첫 번째 방법:

#!/bin/bash

declare -A arr_map

arr_map=([AP]=Fruit [RS]=Sweet)

# Iterate through indexes of array
for keyword in "${!arr_map[@]}"; do
    # Search files containing the "-$keyword" pattern in the name
    # like "-RS" or "-AP". This pattern can be tuned to the better matching.
    for filename in *-"$keyword"*; do
        # if file exists and it is regular file
        if [ -f "$filename" ]; then
            destination=${arr_map["$keyword"]}/"$filename"
            # Remove these echo commands, after checking resulting commands.
            echo mkdir -p "$destination"
            echo mv -iv "$filename" "$destination"
        fi  
    done
done

두 번째 방법:

#!/bin/bash

declare -A arr_map

arr_map=([AP]=Fruit [RS]=Sweet)

# Iterate through all files at once
for i in *; do
    # If the file is a regular and its name conforms to the pattern
    if [[ -f "$i" && "$i" =~ [A-Za-z]+-[A-Z]+[0-9]+ ]]; then
        # trim all characters before the dash: '-' from the beginning
        keyword=${i#*-}
        # trim all digits from the ending
        keyword=${keyword%%[0-9]*}

        # if the arr_map contains this keyword
        if [[  ${arr_map["$keyword"]} != "" ]]; then
            destination=${arr_map["$keyword"]}/$i
            # Remove these echo commands, after checking resulting commands.
            echo mkdir -p "$destination"
            echo mv -iv "$i" "$destination"
        fi
    fi
done

관련 정보