在linux中均匀分隔注释的功能

时间:2018-05-13 07:39:11

标签: linux

您好我正在linux中编写一个自定义函数,用于在注释指示符后放置四个空格。我不熟悉在linux中编写代码,我更擅长阅读它而不是写出来。评论用“;”表示字符。到目前为止,这是我在草案中的内容。这是使用putty进行bash模拟器的基本linux。

commentPlacer()
{

typeset -i count1=0  #iterator for first loop
typeset -i count2=0  #iterator for secod loop
len= ${#$1}  #length of argumnent
comment=";"
space= " "
comIndex=${$1#/;/}  #index of the comment
commentSpace= ";    "  #the comment indicator with the proper spacing

for(( count1; count1 <= len; count1++ ))  #loop to check if there is a comment on the line
    if [[ $1[count] == comment ]]
        for (( count2; count2 < $1[count1]; count2++ ))
                if [[ $1[count2] != commentSpace  ]]  #if the line doesn't have enough spacing in the comment use commentSpace variable 
                    then echo ${{$1:0:comIndex - 1} + commentSpace + {$1:commentSpace + 1: -1}} #cut off line before comment indicator and replace the line with the proper spacing.
                fi
        done
    fi
done
}

代码用于迭代和参数,检查行中是否有;,如果有,它将在';'之前放置四个空格表明评论。我得到的错误是代码第17行的'fi'是语法错误。再一次,我更像是一个javascript编码器,如果有人能给我一个正确方向的观点,我将非常感谢它,我正在学习linux。结果应采用以下代码:

commentPlacer x="example" ;This line is a comment.

将其重新格式化为:

x="example"    ;This line is a comment.

2 个答案:

答案 0 :(得分:1)

假设这是在bash shell脚本中......

for个循环丢失do,而您的第一个if语句丢失then。此外,bash不会将字符串与+连接起来,某些变量扩展似乎缺失$,并且大多数扩展都是不加引号的。而且您无法使用$varname[index]索引到字符串。

使用sed可以完成同样的事情:

sed 's/;[[:blank:]]*/;    /' file

如果你真的想把它写成shell函数,我强烈建议你遵循正确的开发方法,并在每次更改后测试你的代码。您也可以使用https://www.shellcheck.net/网站检查代码的语法。

答案 1 :(得分:0)

您不会告诉您编码的问题中的不完整代码是哪种语言。我猜测它是bash或其他一些POSIX。

然后仔细阅读documentation of bash。你应该至少编码

for (( count1; count1 <= len; count1++ )) ; do
# more code here
done

if [[ $1[count] == comment ]]; then
# more code here
fi

但另见test(1);你可以使用[ "$1[count]" -eq comment ]

当然,你的commentPlacer shell函数应该正确调用,也许(使用quoting)和

commentPlacer 'x="example"' ';This line is a comment'.