--Create an empty file with the file name specified by the argument --If a file with the same name already exists, number it and create it. --If a numbered file also exists, create it with a number one higher than that number.
#!/bin/bash
file=$1
if [[ -e ${file} ]]; then
	maxnumber=$(find . -mindepth 1 -maxdepth 1 -printf "%f\n" \
ã ã| grep -e "^${file}\$" -e "^${file}_[0-9][0-9]*\$" \
	| sed "s/^${file}_\\{0,1\\}//" \
	| sed 's/^$/0/' \
	| sort -rn \
	| head -n 1 ) ;
	file+="_$((maxnumber+1))"
fi
	touch $file
#find current directory(.)Search the file list of
  find . -mindepth 1 -maxdepth 1 -printf "%f\n" 
  # -with mindepth 1-Limit the hierarchy searched by maxdepth 1 to current only
  # -Printf prints only the file name excluding the directory name(%f)Separate with a line break (\nīŧ
 #Search for unnumbered and numbered files with grep
   grep -e "^${file}\$" -e "^${file}_[0-9][0-9]*\$" 
   # -Use regular expressions as an e option
 #"file name_"File name" in "Number"_Only the number is output except
   sed "s/^${file}_\\{0,1\\}//"
   # {0,1}Represents 0 to 1 or less repetitions of the previous character,_Match with or without
   #that time{}Escape(\)Is necessary.\Because it needs escaping itself\\Becomes
#Unnumbered files will be blank lines, so replace them with 0
  sed 's/^$/0/' 
  #ã^The characters that follow match the beginning of the line,$Indicates that the previous string is a line end match
  #  ^$Points to a blank line because nothing is written between
#Sort in descending order of numbers
  sort -rn
  #  -r Option to sort in reverse order
  #  -n Options to consider strings as numbers
#Output only the largest number
  head -n 1 
  # -n 1 Output only the first line
With the commands so far, I was able to get the largest number of duplicate file names. The execution result is assigned to the variable maxnumber by enclosing these commands in command substitution $ ().
From here, add a new number and create a file.
#In the file name, "_Give "number"
  file+="_$((maxnumber+1))"
  #Add 1 to maxnumber and add 1 to the file name_Add "number"
#File creation
  touch ${file}
If the file name is not duplicated, it will be created as it is without a number.
Recommended Posts