UNIX - formatting another shell script - using awk in sed

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
# usage: fsplit file1 file2
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
# usage: fsplit file1 file2
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 #g"

          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'//' )
#use_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 #g"

, , , /case/while/in a/n {, ), / "layer times", . , sed/awk. ?

, , .

+4
2

, , - .

sed 'memory', (, begin | do |...) , (, end | done |...). - , .

awk bash, .

+2

, , script. Google "shell script beautifier", , . MAYBE C "indent" "cb" script, .

+1

Source: https://habr.com/ru/post/1541426/


All Articles