shell - UNIX - 格式化另一个 shell 脚本 - 在 sed 中使用 awk

标签 shell unix awk sed format

嗨,我想编写一些程序来随机格式化另一个脚本代码。您有一个 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 一起工作。建议?

也许您也看到了另一种方法,我很乐意提供一些提示。

最佳答案

您需要存储的唯一信息是当前代码块的深度。

选择一些字符并在您进入新 block 时将其添加到 sed 的“内存”中(例如 begin|do|...),并在退出 block 时删除一个字符(例如 end|done|...)。在每行的开头根据内存的大小添加空格 - 您可以通过将字符一个接一个地移动到第二个内存来实现它。

但我建议使用 awk 或 bash,因为它们更合适。

关于shell - UNIX - 格式化另一个 shell 脚本 - 在 sed 中使用 awk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23784605/

相关文章:

file - 如何将目录中的所有文件名保存到 bash 中的文本文件?

bash - 在最后一行打印最后一个字段

html - 如何使用awk格式化html中的文本

arrays - 如何将数组传递给函数并且对数组的更新反射(reflect)在函数之外

linux - 这两个用于运行 shell 脚本的命令有什么区别?

C 编程 - execlp() 有帮助吗?

java - 从 Java 运行 apachetop

unix - 如何在unix中使用find排除带有大小条件的文件夹和文件?

bash - awk 或 Sed : Replace text between special characters (delimiters)

c++ - Makefile 改头换面——几乎完成,希望得到反馈