bash make directories using specific text from filenames code example

Example: bash make directories using specific text from filenames

# Basic syntax:
for file in /input/directory/search_pattern; do
	substring=${file:start#:length}
	mkdir "/output/directory/prepended_text_${substring}_appended_text"
done

# Where:
#	- The search_pattern should return the set of files you want to
#	use for making the new directories
#	- The substring function takes the start character number and the 
#	length of the substring to use

# Example usage:
# Say you have a directory with the following files and you want to use
# the middle part of the consistent filenames to make new directories:
filename_ABC_123.txt
filename_DEF_123.txt
filename_GHI_123.txt
some_other_file_in_the_directory.txt

for file in ./*123.txt; do # Process files in current directory that end in 123.txt
	substring=${file:11:3} # Use 
	mkdir "/output/directory/prepended_text_${substring}_appended_text"
done

# The /output/directory/ would now have subdirectories named:
prepended_text_ABC_appended_text
prepended_text_DEF_appended_text
prepended_text_GHI_appended_text

Tags:

Misc Example