January 7, 2024
When managing files in a directory, there are occasions where you might have a collection of files prefixed with a common identifier, such as “filename - disk x.” In such cases, organizing these files into separate folders based on this shared prefix can streamline file management.
The command is a simple yet powerful one-liner that uses a Bash for
loop to iterate through files in a directory. For each file, it extracts the prefix using the awk
command, creates a directory with that prefix (if it doesn’t exist), and then moves the file into that newly created folder.
cd
into your directory, preferably a copy of the directory incase the command doesn’t meet your expectations.
for file in *; do prefix=$(echo "$file" | awk -F ' - ' '{print $1}') mkdir -p "$prefix" mv "$file" "$prefix/" done
or
for file in *; do prefix=$(echo "$file" | awk -F ' - ' '{print $1}'); mkdir -p "$prefix"; mv "$file" "$prefix/"; done
Use with Caution: Ensure the files within the directory follow a consistent naming pattern with a shared prefix. Review the command and customize it based on the specific prefix or delimiter used in your filenames. This command is efficient for quickly organizing files into folders based on a shared prefix, aiding in better file management and organization.