I have a directory with a bunch of backup files like this:
projectA20210901.gz
projectA20210902.gz
projectB20210901.gz
projectB20210902.gz
I would like to move all projectA*
files to ./projectA/
and all projectB*
files to ./projectB/
creating the subdirectories if they don't already exist.
The project names before the date 2021...
vary and need to be extracted from the file name, but the date is always there and will always begin with 202
- i.e. 2021, 2022, etc. - we don't need to worry about what happens after 2029 :)
Parameter Expansion can be used to extract the project name, which will be the subdirectory name:
$ string=projectA20211103-23.gz
$ echo ${string%202*}
projectA
How can that be put into a script to run for all files in the current directory? Folders and symlinks should be ignored.
-p
flag does take care of that). Soshopt -s nullglob; gz=( *.gz ); for f in "${gz[@]}"; do tmp="${f%%[0-9]*}"; mkdir -p "$tmp"; mv -- "$f" "$tmp"; done