Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

shell - How to increase value of a text variable in a file

file1.text contains below data.

VARIABLE=00
RATE=14
PRICE=100

I need to increment value by 1 only for below whenever I want.

VARIABLE=00 file name: file1.txt

output should be incremented by 1 every time.

output will be like below

VARIABLE=01

in next run VARIABLE=02 and so on....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Could you please try following, written and tested with shown samples in GNU awk.

awk 'BEGIN{FS=OFS="="} /^VARIABLE/{$NF=sprintf("%02d",$NF+1)} 1' Input_file > temp && mv temp Input_file

Explanation: Adding detailed explanation for above.

awk '                             ##Starting awk program from here.
BEGIN{                            ##Starting BEGIN section of this program from here.
  FS=OFS="="                      ##Setting FS and OFS as = here.
}
/^VARIABLE/{                      ##Checking condition if line starts from VARIABLE then do following.
  $NF=sprintf("%02d",$NF+1)       ##Adding 1 last field and saing it to last field with 2 digits value.
}
1                                 ##1 will print the current line.
' Input_file > temp && mv temp Input_file                      ##Mentioning Input_file name here.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...