Home > Mobile >  How to create a list of sequentially numbered folders using an existing folder name as the base name
How to create a list of sequentially numbered folders using an existing folder name as the base name

Time:10-25

I've done a small amount of bash scripting. Mostly modifying a script to my needs.
On this one I am stumped. I need a script that will read a sub-folder name inside a folder and make a numbered list of folders based on that sub-folder name.

Example: I make a folder named “Pictures”. Then inside I make a sub-folder named “picture-set” I want a script to see the existing sub-folder name (picture-set) and make 10 more folders with sequential numbers appended to the end of the folder names. ex: folder is: Pictures sub-folder is: picture-set

want to create: “picture-set-01” “picture-set-02” “picture-set-03” and so forth up to 10. Or a number specified in the script.

The folder structure would look like this:

/home/Pictures/picture-set

/home/Pictures/picture-set-01

/home/Pictures/picture-set-02

/home/Pictures/picture-set-03 ... and so on

I am unable to tell the script how to find the base folder name to make additional folders. ie: “picture-set”

or a better option: Would be to create a folder and then create a set of numbered sub-folders based on the parent folder name. ex: /home/Songs - would become:

/home/Songs/Songs-001

/home/Songs/Songs-002

/home/Songs/Songs-003

and so on.

Please pardon my bad formatting... this is my first time asking a question on a forum such as this. Any links or pointers as to proper formatting is welcome.

Thanks for the help.

CodePudding user response:

Bash has a parameter expansion you can use to generate folder names as arguments to the mkdir command:

#!/usr/bin/env bash

# Creates all directories up to 10
mkdir -p -- /home/Songs/Songs-{001..010}

This method is not very flexible if you need to dinamically change the range of numbers to generate using variables.

So you may use a Bash for loop and print format the names with desired number of digits and create each directory in the loop:

#!/usr/bin/env bash

start_index=1
end_index=10
for ((i=start_index; i<=end_index; i  )); do
  # format a dirpath with the 3-digits index
  printf -v dirpath '/home/Songs/Songs-d' $i
  mkdir -p -- "$dirpath"
done

CodePudding user response:

# Prerequisite:
mkdir Pictures
cd Pictures

# Your script:
min=1
max=12
name="$(basename "$(realpath .)")"
for num in $(seq -w $min $max); do mkdir "$name-$num"; done

# Result
ls
Pictures-01  Pictures-03  Pictures-05  Pictures-07  Pictures-09  Pictures-11
Pictures-02  Pictures-04  Pictures-06  Pictures-08  Pictures-10  Pictures-12
  •  Tags:  
  • bash
  • Related