gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:17:32 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com