23 May 2024

Bulk operations in the terminal with Sublime Text

A neat trick for semi-automation of repetitive tasks on/in a group of folders.

Let's say you have a bunch of folders in a directory that you want to perform the same operation on.

$ ls -1
folder1
folder2
folder3
...
folderN

Sublime Text is my swiss-army knife of choice for general text editing can be started from the command line using the subl command-line tool.

$ subl -h
Sublime Text build 4169

Usage: subl [arguments] [files]         Edit the given files
   or: subl [arguments] [directories]   Open the given directories
   or: subl [arguments] -- [files]      Edit files that may start with '-'
   or: subl [arguments] -               Edit stdin
   or: subl [arguments] - >out          Edit stdin and write the edit to stdout
...

Notice that last line of usage info, which declares that sublime text can allow you to edit content provided from stdin and then provide the final edit to stdout!

So, back to the original premise: let's say I wanted to perform some operation (like ls | wc -l) in each folder. I could pipe the output of ls -1 to subl - >out, compose a script from the listing, and (if I'm feeling brave) pipe that ad-hoc script to bash:

$ ls -1 | subl - >out | bash

When the Sublime Text buffer appears, it will contain the output of ls -1:

folder1
folder2
folder3
...
folderN

Using multiple cursors I can easily transform those contents to look like this:

cd folder1; ls -1 | wc -l; cd ..
cd folder2; ls -1 | wc -l; cd ..
cd folder3; ls -1 | wc -l; cd ..
...
cd folderN; ls -1 | wc -l; cd ..

Upon closing the buffer the ad-hoc script I've just authored will be executed and its output will appear in the terminal:

/path/to/folder1
      33
/path/to/folder2
       6
/path/to/folder3
      15
...
/path/to/folderN
       9

I'll be using this technique to semi-automate a bunch of common chores (like updating dependencies, etc...).

Enjoy!