I have a ton of screenshots on my desktop (it's the default location where they're saved) with titles of the form "Screen Shot 2020-10-11 at 7.08.12 PM.png" and I'd like to use a bash script with regex on the "Screen Shot" bit to move any such file from my desktop into a folder I created called "screenshots".
Right now, I'm playing around with find . -regex Screen*.*?.png
but it's not quite working (it gives find: Screen Shot 2020-10-11 at 7.11.09 PM.png: unknown primary or operator
).
I'm also not sure how I'd even use the output once it does find all the correct files to move them to a folder. Could you somehow iterate over all files in a folder using for i in seq 1 100
or something of the like?
You don't actually even need -regex here:
find . -type f -name 'Screen Shot*png' -maxdepth 1 -exec echo mv "{}" screenshots \;
You can run this command safely as it will not do anything but print
what it would do. Remove echo
to actually run mv
.
All options used are documented in man find
but in short:
-type f
will make find
look only for files, not directories. This
is useful in case you have a directory that matches -name
- we don't
want to touch it.
-maxdepth 1
will only look fire files in the same directory level -
it's very useful here because you might already have some files that
match the -name present in screenshots
directory - we want to leave
them alone.
-name
accepts shell pattern, not regex. We could of course use -regex
here but I prefer -name
because shell patterns are shorter and easier to use here.
{}
is a placeholder that will be replaced will the name of found
file.
\;
is a literal semicolon, escaped to prevent it from being
interpreted by shell that ends command specified with -exec
.