【发布时间】:2014-05-21 13:26:15
【问题描述】:
您好,我想编写一些程序来随机格式化另一个脚本代码。你有一个 testdata.sh 代码,格式如下:
#!/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"
您将脚本称为“format_it.sh”...
sh format_it.sh -t < testdata.sh
这意味着使用制表符进行格式化。 否则你可以使用
sh format_it.sh -s5 < testdata.sh
这意味着 f.e.使用 5 个空格进行格式化。
我想做的就是以这种方式格式化它。总是在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"
到目前为止,我的脚本看起来像这样..
#!/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
问题线是:
sed -r "s#(if|case|while|for)#\n awk "BEGIN \{ ORS=\"\"; for (i=0;i<=$layer;i++)
print \"\t\" \}" \1 #g"
我想要这行做的,是为文本中的每个 if/case/while/for 替换它 a /n {将其移至新行),然后使用“图层时间”选项卡/空格将其格式化。 我不知道如何使这条线与 sed/awk 一起工作。建议?
也许您也看到了另一种方法,我很乐意提供一些提示。
【问题讨论】: