Hi, I would like to write some program to format a random other script code. You have the code testdata.sh in the form:
#!/bin/sh
total=0; lost=0
while
read next
do
total=`expr $total + 1`
for i in *; do
if test -d $dir/$i
then
cd $dir/$i
while echo "$i:" ; read x ; do eval $x ; done
cd ..
fi
done
case "$next" in
*[A-Za-z]*) echo "$next" >> $1 ;;
*[0-9]*) echo "$next" >> $2 ;; *) lost=`expr $lost + 1`
esac
done ; echo "$total lines read, $lost thrown away"
You call your script "format_it.sh" ...
sh format_it.sh -t < testdata.sh
which means using tabs for formatting. Otherwise you can use
sh format_it.sh -s5 < testdata.sh
which means fe to use 5space for formatting.
What I want to do is format it that way. Always after while / for / case / if.
#!/bin/sh
total=0; lost=0
while
read next
do
total=`expr $total + 1`
for i in *; do
if test -d $dir/$i
then
cd $dir/$i
while echo "$i:" ; read x ; do eval $x ; done
cd ..
fi
done
case "$next" in
*[A-Za-z]*) echo "$next" >> $1 ;;
*[0-9]*) echo "$next" >> $2 ;;
*) lost=`expr $lost + 1`
esac
done ;
echo "$total lines read, $lost thrown away"
So far, my script looks like this.
#!/bin/sh
function use_t(){
layer=0
while read a; do
if [ -n "$(echo $a | egrep "if|case|while|for")" ]; then
layer=$((layer+1))
sed -r "s#(if|case|while|for)#\n awk "BEGIN \{ ORS=\"\"; for (i=0;i<=$layer;i++)
print \"\t\" \}" \1
elif [ -n "$(echo $a | egrep "fi|esac|done")" ]; then layer=$(layer-1))
fi
done
}
if [ "$1" = "-t" ] ; then
use_t
elif [ -n "$(echo "$1" | grep "^\-s[1-9][0-9]*$")" ] ; then
n_spaces=$(echo $1| sed 's/'-s'//' )
else
echo "ERROR - wrong input of parameters"
fi
Problem line:
sed -r "s#(if|case|while|for)#\n awk "BEGIN \{ ORS=\"\"; for (i=0;i<=$layer;i++)
print \"\t\" \}" \1
, , , /case/while/in
a/n {, ), / "layer times", .
, sed/awk. ?
, , .