How to increase value of a text variable in a file

瘦欲@ 提交于 2021-01-28 21:24:55

问题


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....


回答1:


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.



回答2:


You can do it quite simply as a one-liner in Perl:

perl -i -pe '/^VARIABLE=/ && s/(\d+)/$&+1/e' file

In case you are unfamiliar with Perl, that says...

Run Perl and modify file in-place. if you come to any lines containing VARIABLE=, substitute the digits on that line with an expression calculated as "whatever the number was +1"

Note that Perl is a standard part of macOS - i.e. automatically included with all versions.



来源:https://stackoverflow.com/questions/63325606/how-to-increase-value-of-a-text-variable-in-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!