【问题标题】:UNIX - formatting another shell script - using awk in sedUNIX - 格式化另一个 shell 脚本 - 在 sed 中使用 awk
【发布时间】: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 一起工作。建议?

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

【问题讨论】:

    标签: shell unix awk sed format


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您需要一个理解该语言的解析器来执行此操作,您无法使用简单的脚本可靠地完成此操作。谷歌“shell script beautifier”,你会发现一些声称可以做到这一点的工具。可能 C 美化器“缩进”或“cb”甚至适用于 shell 脚本,但我对此表示怀疑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 2017-05-01
        相关资源
        最近更新 更多