2017-03-18 111 views
0

我想“重新排序”我正在写的一个大型BASH脚本中的一些变量赋值。目前,我必须手动执行此操作,而且这非常耗时。 ;)bash脚本按顺序重写数字

如:

(some code here) 
ab=0 
(and some here too) 
    ab=3 
(more code here) 
cd=2; ab=1 
(more code here) 
    ab=2 

我希望做的是运行一个命令,可以重新排序“AB”的分配值,所以我们得到:

(some code here) 
ab=0 
(and some here too) 
    ab=1 
(more code here) 
cd=2; ab=2 
(more code here) 
    ab=3 

的缩进存在,因为它们通常构成代码块的一部分,如'if'或'for'块。

变量名称将始终相同。脚本中的第一次出现应为零。我认为如果某事(如sed)可以搜索'ab ='后跟一个整数,那么根据递增值更改该整数,这将是完美的。

希望有人在那里可能知道可以做到这一点的事情。我使用'凯特'进行BASH编辑。

有什么想法?谢谢。

+0

如果这涉及实际解析bash脚本,这将是痛苦的。 – rici

回答

2
$ # can also use: perl -pe 's/\bab=\K\d+/$i++/ge' file 
$ perl -pe 's/(\bab=)\d+/$1.$i++/ge' file 
(some code here) 
ab=0 
(and some here too) 
    ab=1 
(more code here) 
cd=2; ab=2 
(more code here) 
    ab=3 
  • (\bab=)\d+匹配ab=和一个或多个数字。 \b是词边界标记,使得像dab=4字不匹配
  • e改性剂允许替换部分使用Perl代码
  • $1.$i++ab=字符串连接和$i值(这是0默认情况下)然后$i被递增
  • 使用perl -i -pe用于就地编辑
+0

谢谢@Sundeep,我一直在使用你的perl命令,它的工作完美无瑕。 :) – teracow

1

@teracoy:@try:

awk '/ab=/{sub(/ab=[0-9]+/,"ab="i++);print;next} 1' Input_file 
+3

'; print; next'可以被删除,因为每一行都由'1'打印......如果一行中有多个匹配,则'gsub' – Sundeep

+2

@Sundeep'gsub()'只会增加'i'一次为整个行,你需要一些'sub()'调用的循环多次增加'我',但这是不平凡的。 –

+1

@EdMorton不知道这一点,谢谢..只是假设它: -/ – Sundeep

1

与GNU AWK多炭RS,RT,和gensub():

$ awk -v RS='\\<ab=[0-9]+' '{ORS=gensub(/[0-9]+/,i++,1,RT)}1' file 
(some code here) 
ab=0 
(and some here too) 
    ab=1 
(more code here) 
cd=2; ab=2 
(more code here) 
    ab=3 

如果需要,可以使用awk -i inplace ...进行就地编辑。

+0

请指教awk的什么味道允许-i选项,因为gawk似乎认为它是includefile? – grail

+0

gawk - 与'-i inplace'参数相比,不像在sed中'-i'并不意味着'inplace',而是'-i'意味着'include'和'inplace'是你告诉它的扩展名包括。请参阅https://www.gnu.org/software/gawk/manual/gawk.html#Extension-Sample-Inplace –

+1

非常感谢您的信息:) – grail