I have a simple bash script, called *print_code.sh*, that takes a file name, and prints out the file with line numbers.
Here it is:
FILE=$1
line=0;
numLines=`wc -l $FILE | sed 's/ .*$//'`
digits=`echo "l($numLines)/l(10)+1" | bc -l`
digits=`echo "0$digits" | sed 's/\..*$//'`
for i in `cat $FILE | sed 's/ /_=SPACE=_/g'`; do
line=`echo $line + 1 | bc`;
i=`echo $i | sed 's/_=SPACE=_/ /g'`;
printf "%${digits}d | %s\n" $line "$i"
done
Here is a silly source file in an imaginary language:
var x = 1
var y = 2
var z = 3
func dostuff {
var a
var b
x = x + 1
y = y + 1
z = z + 1
a = x + y + z
b = a
}
Here is the output with the line numbers:
01 | var x = 1
02 | var y = 2
03 | var z = 3
04 | func dostuff {
05 | var a
06 | var b
07 | x = x + 1
08 | y = y + 1
09 | z = z + 1
10 | a = x + y + z
11 | b = a
12 | }
There are (at least) two functional problems with *print_code.sh*:
- Any blank lines will be ignored - which will break the numbering
- If the source file contains tabs, the tab character will be treated like a newline character
Also, it is hackish in places, because I don't know bash that well - particularly substituting the space character with a placeholder =SPACE=, so we can iterate over each line using for.
What is the best way this code can be cleaned up such that is not as hackish, and such that the above functional problems go away?
Are there any other functional problems that I have missed?