증분 숫자 접미사를 사용하여 파일 이름을 만드는 방법

증분 숫자 접미사를 사용하여 파일 이름을 만드는 방법

저는 작업 중인 연구 프로젝트의 데이터를 기록하기 위해 두 개의 스크립트를 자동으로 시작하고 작업이 완료되면 자동으로 데이터용 디렉터리를 생성하고 해당 디렉터리로 데이터를 이동하는 셸 스크립트를 작성하고 있습니다. 프로그램은 "Trials"라는 폴더가 아직 없으면 생성하고 Trial 폴더 내에서 "Trial$n"이라는 폴더를 확인합니다. 여기서 n은 0부터 시작하는 증가하는 정수입니다. 프로그램이 실행될 때마다 생성되는 폴더의 이름이 1씩 증가하도록 하는 아이디어입니다. 명명 시스템을 제외하고 전체 프로그램이 잘 작동합니다. 처음 코드를 작성할 때는 잘 작동했지만 "Trial0...Trial2" 폴더를 삭제하면 시도 0~2에 대한 폴더가 존재하는지 여부에 관계없이 다음으로 생성될 폴더는 "folder3"이 됩니다. 이 작업은 "Trial13" 폴더가 생성될 때까지 계속됩니다. 이제 프로그램은 매번 "Trial13"을 덮어씁니다. 여기 내 코드가 있습니다. 관련 줄은 149:187입니다.

  1 #!/bin/bash
  2 #-----------------------------------------------------------------------------
  3 #The purpose of this script it to automate and streamline the data collection
  4 #and analysis process for the touchless respitatory monitor. The script will
  5 #prompt you for the paths of the themral camera executable
  6 #(seek_viewer, usually in the libseek-thermal library), the path of the
  7 #main python script (SingleThreadedFaceDetectionV6), and the path of
  8 #removable media to which the files will be saved. It will then give you
  9 #command prompts to guide you through the process and put a fully-formatted
 10 #data folder in the removable media such that the folder is immediately
 11 #compatable with the MATLAB script on PC.
 12 
 13 #NOTE: Sometimes the thermal camera won't initialize properly and the program
 14 #needs to be restarted until it works.
 15 
 16 #Author:    Caleb Schreier
 17 #Date:      7 June 2022
 18 #OS:        Raspbian GNU/Linux 10 (buster)
 19 #Kernel:    Linux 5.10.103-v7l+
 20 #Architecture:  arm
 21 #Python:    3.7
 22 #Numpy:     1.22.4
 23 #-----------------------------------------------------------------------------
 24 
 25 #Import Settings
 26 source launcherSettings.txt
 27 
 28 #If setting don't exist, prompt user for settings
 29 if [ "$remember" != "y" ];
 30 then
 31 
 32 echo
 33 echo Please format paths as /folder/.../targetfolder
 34 echo
 35 echo Specify path to folder containing Thermal Camera Executable
 36 echo \(libseek_viewer\)
 37 echo
 38 
 39 read -r thermalPath
 40 
 41 echo
 42 echo Specify path to folder containing Python Script 
 43 echo \(SingleThreadedFaceDetectionV6\)
 44 echo
 45 
 46 read -r opticalPath
 47 
 48 echo
 49 echo Specify path to which data should be saved
 50 echo for flash drive, use /media/pi/DRIVENAME
 51 echo
 52 
 53 read -r mediaPath
 54 
 55 echo
 56 read -r -p "remember these settings? [y/n] " remember
 57 echo
 58 
 59 #Write settings to launcherSettings.txt
 60 case "$remember" in
 61     [yY][eE][sS]|[yY])
 62         echo Saving to file...
 63         echo "remember=y" | sudo tee launcherSettings.txt
 64                 echo "opticalPath=$opticalPath" | sudo tee -a launcherSettings.txt
 65                 echo "thermalPath=$thermalPath" | sudo tee -a launcherSettings.txt 
 66                 echo "mediaPath=$mediaPath" | sudo tee -a launcherSettings.txt
 67 
 68         ;;
 69     *)
 70         echo "remember=n" | sudo tee launcherSettings.txt
 71         echo Settings not remembered.
 72         ;;
 73 esac
 74 
 75 else
 76 
 77 #if settings already exist, ask user whether to keep them. if not, reprompt for new settings
 78 echo
 79 read -r -p "Keep stored settings? [y/n] " modify
 80 
 81 if [ "$modify" != "y" ];
 82 then
 83 
 84 echo
 85 echo Please format paths as /folder/.../targetfolder
 86 echo
 87 echo Specify path to folder containing Thermal Camera Executable
 88 echo \(libseek_viewer\)
 89 echo
 90 
 91 read -r thermalPath
 92 
 93 echo
 94 echo Specify path to folder containing Python Script
 95 echo \(SingleThreadedFaceDetectionV6\)
 96 echo
 97 
 98 read -r opticalPath
 99 
100 echo
101 echo Specify path to which data should be saved
102 echo for flash drive, use /media/pi/DRIVENAME
103 echo
104 
105 read -r mediaPath
106 
107 echo
108 read -r -p "remember these settings? [y/n] " remember
109 echo
110 
111 case "$remember" in
112         [yY][eE][sS]|[yY])
113         echo Saving to file...
114                 echo "remember=y" | sudo tee launcherSettings.txt
115                 echo "opticalPath=$opticalPath" | sudo tee -a launcherSettings.txt
116                 echo "thermalPath=$thermalPath" | sudo tee -a launcherSettings.txt
117                 echo "mediaPath=$mediaPath" | sudo tee -a launcherSettings.txt
118                 ;;
119         *)
120         echo "remember=n" | sudo tee launcherSettings.txt
121                 echo Settings not remembered.
122                 ;;
123 esac
124 
125 
126 fi
127 fi
128 
129 #initiate thermal camera
130 echo
131 echo Beginning thermal camera...
132 echo
133 
134 x-terminal-emulator -e "cd $thermalPath; ./seek_viewer -m[file]"
135 
136 #Initiate script for optical camera and analysis. Both this and the thermal camera
137 #program can be ended with CTRL + C
138 echo Beginning Python Script...
139 echo
140 echo Use CTRL + C to end script
141 echo
142 
143 python $opticalPath/SingleThreadedFaceDetectionV6.py
144 
145 wait
146 
147 echo creating file structure...
148 
149 sudo mkdir -v -p $mediaPath/trials
150 
151 #make numbered trial folder at the smallest unused number
152 echo testing for unused directory name...
153 
154 n=0
155 found=0
156 
157 while [ $found -eq 0 ];
158 do
159     if test -d "$mediapath/trials/trial$n";
160 
161     then
162 
163         echo Folder \"trial$n\" is taken.
164 
165         ((n+=1))
166 
167     else 
168 
169         echo found free space at folder $n
170             #make subdirectories
171             sudo mkdir -v -p $mediaPath/trials/trial$n/Thermal
172         sudo mkdir -v -p $mediaPath/trials/trial$n/Optical
173             #move photos and trial data to respective directories (may take a while)
174         echo moving thermal photos...
175             sudo mv -i $thermalPath/*.jpeg $mediaPath/trials/trial$n/Thermal
176             sudo mv -i $thermalPath/oldImages/*.jpeg $mediaPath/trials/trial$n/Thermal
177         echo moving optical photos...
178             sudo mv -i $opticalPath/*.jpeg $mediaPath/trials/trial$n/Optical
179             echo moving metadata...
180             sudo mv -i $opticalPath/avgValues.txt $mediaPath/trials/trial$n
181             echo move complete. Rerun launcher.sh to take another trial or eject media to run MATLAB code on PC
182 
183         found=1
184 
185     fi
186 
187 done
188 
189 echo Filing data from trial under folder \"$mediapath/trials/trial$n\"

답변1

이 샘플 조각을 파일에 넣고 반복적으로 실행해 보세요. 이전 디렉터리를 삭제하면 다음에 실행할 때 다시 사용됩니다.

#!/bin/bash
#
base='trials'     # Base directory where everything lives
prefix='trial'    # Prefix of subdirectory name
n=0               # Starting suffix number

mkdir -p "$base"
while [ -d "$base/$prefix$n" ]; do ((n++)); done

echo "Will create and use $base/$prefix$n"
mkdir "$base/$prefix$n"

생성된 디렉터리는 숫자 오름차순으로 나열되지 않습니다. 디렉터리 수에 상한이 있는 경우 숫자 앞에 0을 붙일 수 있습니다(예: 4 대신 0004).

프로덕션 코드에서는 여기에서 했던 것처럼 변수를 큰따옴표로 묶는 것을 잊지 마세요. 이렇게 하면 쉘이 해당 단어를 별도의 단어로 확장하려고 시도하는 것을 방지할 수 있습니다.

관련 정보