Skip to content

Instantly share code, notes, and snippets.

@jryio
Last active December 8, 2015 07:28
Show Gist options
  • Save jryio/2a8710853d510d78d9c3 to your computer and use it in GitHub Desktop.
Save jryio/2a8710853d510d78d9c3 to your computer and use it in GitHub Desktop.
Formatting assembly comments using Bash
#!/bin/bash
#
# Programmer: Jacob Young
# Filename: comments.sh
# Date: Mon Dec 7 2015
# Class: COSMC-171
#
# Assignment 1
# This script will align comments in an assmebly language file
# Lines which start with a comment (;) will not be modified
# Comments which come after a line of code, should be aligned
# 4 columns after the longest line of code.
# Array to hold all lines of input
Line=()
# The longest number of "code characters"
declare -i Longest=0
# Reading input from stdin
while IFS='' read line; do
Lines+=("$line")
done
# Check all lines, find the line with the most "code characters"
for line in "${Lines[@]}"; do
# If the line begins with a comment, skip it
if [[ ${line:0:1} == ";" ]]; then
continue
else
temp="${line%;*}" # Taking out the inline comment
temp="$(echo -e "${temp}" | sed -e 's/[[:space:]]*$//')" # Using sed to remove trailing whitespace
#echo "$temp"
# If the number of code characters is longer than the previous max, set the new max
if [[ "${#temp}" -gt "$Longest" ]]; then
Longest="${#temp}"
fi
fi
done
# At this point, we need to shift all lines with comments to be at position 27+4
FinalColumn=$(( $Longest + 5 ))
for line in "${Lines[@]}"; do
# Skipping lines with comment at the start
if [[ ${line:0:1} == ";" ]]; then
echo "$line"
else
semicolon=$(( $(expr index "$line" ';') - 1 ))
offset=$(( $FinalColumn - $semicolon - 1 )) # Calculate the offset for the current line
whitespace=$(printf "%-"$offset"s" "") # Create some whitespace to fill in
whitespace="${whitespace// / }" # Do some bash magic
old_comment="${line:$semicolon}"
new_comment="$whitespace""${line:$semicolon}"
echo "${line/$old_comment/$new_comment}"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment