rss_feed

Batch Convert 4-Space Indentations to 2-Space

1 March 2018

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.

How would you rate this post?

About the Author

Alex Seifert
Alex is a developer, a drummer and an amateur historian. He enjoys being on the stage in front of a large crowd, but also sitting in a room alone, programming something or writing about history.

Related Posts

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>