2017-03-18 65 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