Skip to content

Instantly share code, notes, and snippets.

@AyresMonteiro
Last active December 1, 2021 17:15
Show Gist options
  • Save AyresMonteiro/15bf6d8be12db7f0960c39813a299907 to your computer and use it in GitHub Desktop.
Save AyresMonteiro/15bf6d8be12db7f0960c39813a299907 to your computer and use it in GitHub Desktop.
Creates directories with the same name of the files and moves files inside them (Shell script)
#!/bin/bash
# The line above is a shebang. You can read more about it at https://en.wikipedia.org/wiki/Shebang_(Unix).
# Goes to base dir
cd ~/your/dir
# Iterate over directories in base directory.
for dir in *
do
# For each directory, iterate over files.
# ALERT 1: THIS CODE ORIGINALLY MOVES ONLY C FILES.
# ALERT 2.1: YOU CAN MODIFY ".c" EXTENSION BELOW TO ANY OTHER THAT YOU DO PREFER
for file in "$dir/"*.c
do
# If file exists, run. Otherwise, just continue the loop
if [ -a "$file" ]; then
# Returns a copy of the filename without the "#" character and stores it in newDir variable
newDir=${file//#}
# Returns a copy of newDir without the ".c" extension and stores it in newDir variable
# ALERT 2.2: BUT REMEMBER TO CHANGE HERE TOO
newDir=${newDir//.c}
# Generates a new filename based on the original filename
newName=${file//$dir\/#}
# And wraps it into the new dir
newName="$newDir/$newName"
# If new dir does not exist, create it
if [ ! -d "$newDir" ]; then
mkdir -- "$newDir"
fi
# Logs the move operation on console
echo "$file -> $newName"
# Moves file with the new name into the new directory
mv -- "$file" "$newName"
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment