Notes From The Dork Web

Simple Batch Jobs I Keep Having To Look Up

I often use bigger tools for batch tasks instead of smaller ones because I keep forgetting they exist, or expect arcane incantations to be needed to run them. Sometimes arcane incantations are needed but there's often simpler options.

I'll update this now and again when I find something that saves time. I was going to keep this in my Obsidian notes, but knowing my luck I'd need this most at the precise point I don't have access to them.

Images

Bulk resizing images

Got a directory of images? Yes, you can download a GUI tool to resize. Yes, on MacOS you can open your images in Preview, select the images and use the resize tool. But did you know about mogrify? I keep forgetting about it.

Mogrify edits files in-place. Use copies if you don't want to modify originals.

To scale all jpg files by percentage (say 50%), from a shell:

mogrify -resize 50% *.jpg

Batch convert images from one format to another.

Once again this is a job for mogrify. To convert all webp files to png:

mogrify -format png *.webp

Desaturate Images

H/T to @Orrlewin for this one, which I've borrowed from his notes and optimized with mogrify:

mogrify -modulate 100,0,100 *.jpg

The modulate command comes with ImageMagick, and expects 3 numeric arguments in the format brightness,saturation,hue.

Text

Replace text across multiple text files

This is a little more arcane and involves pipes and find, but basically:

find . -type f -print0 | xargs -0 -n 1 sed -i -e 's/from/to/g'

The above will search beneath the current working directory and change all instance of 'from' to 'to', in-place. Note that this includes all directories, which might not be what you want. If you want to exclude any paths (e.g. .git), then use this:

find . ! -regex ".*[/]\.git[/]?.*" -type f -print0 | xargs -0 -n 1 sed -i -e 's/from/to/g'

Replace instances of text in a single file

This is easy to do in vi, vim, neovim. You might not like it but it works for me. Open the file in your editor, use ESC to enter command mode and use:

:%s/foo/bar/g

Use /gi instead of '/g' at the end if you want a case-insensitive replacement.

To replace all instances of 'foo' with 'bar'. If you just want to replace in the next 4 lines, use:

:.,+4s/foo/bar/g

Files

Copy Files Back To Location After Messing Up

I generally work on file copies, but if I mess up and I'm only using a subset of files from a larger folder I can copy the original files back using find and exec. The example below copies in ../masters/ that has the same name as files in the current directory over the existing files in the current directory.

find . -type f -exec cp ../masters/\{\} . \

#batch #commandline #shell #tools