Welcome to OStack Knowledge Sharing 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 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...