Rewrite t2s in Bash (although it is slow)

This commit is contained in:
Ev Bogdanov 2017-08-16 23:43:09 +03:00
parent dea4747965
commit 9416a9e209

49
bin/t2s
View file

@ -1,17 +1,42 @@
#!/usr/bin/env perl
#!/usr/bin/env bash
use strict;
use warnings;
n_spaces="$1"
my $N_SPACES = $ARGV[0] || 4;
if [ ! "$n_spaces" ]; then
n_spaces=4
fi
while (my $line = <STDIN>) {
# Skip empty lines
print "\n" and next if $line !~ m/\S/;
if [ $n_spaces -lt 1 ]; then
echo 'Sorry. Number of spaces should be a positive number'
exit 1
fi
$line =~ m/^(\t*)(.+)$/;
my $n_tabs = length($1);
my $n_spaces = $n_tabs * $N_SPACES;
space=''
i=0
while [ true ]; do
space="$space "
i=$(( $i + 1 ))
if [ $i -eq $n_spaces ]; then
break
fi
done
print ' ' x $n_spaces . "$2\n";
}
while IFS='' read -r line || [[ -n "$line" ]]; do
if [[ ${line:0:1} != ' ' ]]; then
echo "$line"
continue
fi
# Line length
line_len=${#line}
# Get leading tabs and their length
tabs=$(echo "$line" | sed -n 's/^\( *\)\(.*\)$/\1/p')
tabs_len=${#tabs}
line_without_tabs_len=$(( $line_len - $tabs_len ))
line_without_tabs=${line:$tabs_len:$line_without_tabs_len}
spaces=$(echo "$tabs" | sed "s/ /$space/g")
echo "$spaces$line_without_tabs"
done