Batch Convert 4-Space Indentations to 2-Space

While adding a linter to an old project, I wrote the following bash script to convert 4-space indentations to 2-space indentations. It requires the “unexpand” and “expand” packages to be installed which, if you use macOS, are pre-installed.

#!/bin/bash

expand_func () {
  OLD_LENGTH=4        # old indentation length
  NEW_LENGTH=2        # new indentation length
  unexpand -t $OLD_LENGTH "$1" | expand -t $NEW_LENGTH > "$1.tmp"
  mv "$1.tmp" "$1"
}

export -f expand_func

find ./ -name \*.js -exec bash -c 'expand_func {}' \;

This example recursively looks for *.js files starting at the script’s location. Of course, it can be used for any type of file though by simply changing the extension.

This script is based on a solution suggested on StackOverflow.

The code is also available as a Gist on GitHub.

This entry was posted in Development, Linux, Mac, Server and tagged , , , , . Bookmark the permalink. Follow comments with the RSS feed for this postPost a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is kept private. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>