How Do I Trim Whitespace at the End of Text Lines?

Understood.

In that context I would personally use:

  • .trimEnd() (in a KM Execute JavaScript for Automation action), or
  • rstrip() (in a KM Execute a Shell Script action calling Python)

Beyond very short and trivial patterns, Regular Expressions cost a lot of fiddle, puzzlement and debugging, in exchange for rather limited scope.

This forum is remarkably full of posts where the user has started with one problem, and by choosing Regular Expressions has ended up with two problems, so that some permutation of "Regex" actually figures in the way they name their difficulty :slight_smile:

(Regex problems have moved into the foreground, to the extent that the original problem has become occluded)

Time invested in learning anything beyond the most trivial Regular Expressions is really much better invested in experimenting with a scripting language like Python or JavaScript.

They are more readable, give you more flexibility and power, and waste less time.

Using JS here (just because Keyboard Maestro, and the uncertainties of macOS Python versions and locations, make it easier),

Perhaps something like:

(() => {
    "use strict";

    return Application("Keyboard Maestro Engine")
        .getvariable("espacesSuperflues")
        .split("\n")
        .map(x => x.trimEnd())
        .join("\n");
})();

Trim trailling space of each line.kmmacros (2.8 KB)

1 Like