Skip to content

Instantly share code, notes, and snippets.

@Flakebi
Created February 10, 2017 17:23
Show Gist options
  • Save Flakebi/0021624c9c9f01f70c8b02736bff7b7e to your computer and use it in GitHub Desktop.
Save Flakebi/0021624c9c9f01f70c8b02736bff7b7e to your computer and use it in GitHub Desktop.
Beautifully format source code
#!/usr/bin/env bash
# Input: <inputfile> <outputfile>
cp $1 $2
# Remove comments
sed -i 's#//.*##g' $2
# Move to new lines
sed -i 'H;$!d;x;s/;\n*/\n;/g' $2
sed -i 'H;$!d;x;s/\s*{\n*/\n{/g' $2
sed -i 'H;$!d;x;s/\s*}\n*/\n}/g' $2
# Join lines without fancy start
sed -i 'H;$!d;x;s/\n\([^;{}]\)/ \1/g' $2
# Remove unnecessary spaces
sed -i 's/\s*\([!=,<>+=*/:?&|(){}]\+\)\s*/\1/g' $2
sed -i 's/ \+/ /g' $2
# Add spaces at the beginning
sed -i 's/^\([;{}]\)\s*/\1 /g' $2
# Remove trailing whitespaces
sed -i 's/ \+$//g' $2
#Fix first line
sed -i 'H;$!d;x;s/^\s*/; /g' $2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment