Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment with bash

Tags:

I'm stuck trying to increment a variable in an .xml file. The tag may be in a file 100 times or just twice. I am trying to add a value that will increment the amount several times. I have included some sample code I am working on, but when I run the script it will only place a one and not increment further. Advice would be great on what I'm doing wrong.

for xmlfile in $(find $DIRECTORY -type f -name \*.xml); do   TFILE="/tmp/$directoryname.$$"   FROM='><process>'   TO=' value\=""><process>'   i=0   while [ $i -lt 10 ]; do     i=`expr $i + 1`     FROM='value\=""'     TO='value\="'$i'"'   done   sed "s/$FROM/$TO/g" "$xmlfile" > $TFILE && mv $TFILE "$xmlfile" done 

The while loop was something I just placed to test the code. It will insert the <process> but it will not insert the increment.

My end goal:

<process>value="1"</process> <process>value="2"</process> <process>value="3"</process> <process>value="4"</process> 

And so on as long as <process> is present in the file it needs to increment.

like image 728
DᴀʀᴛʜVᴀᴅᴇʀ Avatar asked Nov 14 '12 19:11

DᴀʀᴛʜVᴀᴅᴇʀ


People also ask

Can you use ++ in bash?

Similar to other programming language bash also supports increment and decrement operators. The increment operator ++ increases the value of a variable by one.

Can you do += in bash?

Bash also provides the assignment operators += and -= to increment and decrement the value of the left operand with the value specified after the operator.

How do you increment a variable in UNIX?

or declare i as an integer variable and use the += operator for incrementing its value.


1 Answers

I just tested your code and it seems to correctly increment i.

You could try changing your increment syntax from:

i=`expr $i + 1` 

To

i=$((i+1)) 
like image 190
sampson-chen Avatar answered Sep 18 '22 07:09

sampson-chen