gpt4 book ai didi

linux - Linux中均匀间隔注释的功能

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:41 24 4
gpt4 key购买 nike

嗨,我正在 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.

最佳答案

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

您的两个 for 循环都缺少 do,并且您的第一个 if 语句缺少 then。此外,bash 不会使用 + 连接字符串,某些变量扩展似乎缺少 $,并且大多数扩展都未加引号。并且您无法使用 $varname[index] 对字符串进行索引。

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

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

如果您确实想将其编写为 shell 函数,我强烈建议您遵循正确的开发方法并在每次更改后测试您的代码。您还可以从使用 https://www.shellcheck.net/ 中受益用于检查代码语法的站点。

关于linux - Linux中均匀间隔注释的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50313839/

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