sort by file extension

22. Januar 2022

The following code snippets can be used to arrange all files in the current directory into subdirectories sorted by file extension.

# for bash
for f in *; do fn=$(basename -- "$f"); ext="${fn##*.}"; mkdir -p $ext; mv $f "$ext/"; done
# for fish
for f in *; set fn (basename -- "$f"); set ext (string split -r -m1 . $fn); mkdir -p $ext[2]; mv $f "$ext[2]/"; end

 

Explanation:
The for command loops over all files in the current directory, the basename command removes all but the filename, the ${##*.} or string split command extracts the file extension. mkdir creates the directory and mv moves the file into this directory.

I'm pretty sure, the fish version could be simplified, but hey - it works!