UNIX – 格式化另一个shell脚本 – 在sed中使用awk
发布时间:2020-12-15 21:00:19 所属栏目:安全 来源:网络整理
导读:嗨,我想写一些程序来格式化随机的另一个脚本代码.你有一个像以下形式的testdata.sh代码: #!/bin/sh# usage: fsplit file1 file2total=0; lost=0while read nextdototal=`expr $total + 1`for i in *; doif test -d $dir/$ithencd $dir/$iwhile echo "$i:" ;
嗨,我想写一些程序来格式化随机的另一个脚本代码.你有一个像以下形式的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替换它 也许你看到了另一种方式,我会很高兴一些提示. 解决方法
您需要存储的唯一信息是当前代码块的深度.
输入一个字符并在输入新块时将其添加到sed’memory'(例如begin | do | …)并在退出块时删除一个(例如end | done | …).在每行的开头根据内存的大小添加空格 – 您可以通过将字符逐个移动到第二个内存来实现. 但我建议使用awk或bash,因为它们更合适. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |