How to increment number in a file

Viewed 34829

I have one file with the date like below,let say file name is file1.txt:

2013-12-29,1

Here I have to increment the number by 1, so it should be 1+1=2 like..

2013-12-29,2 

I tried to use 'sed' to replace and must be with variables only.

oldnum=`cut -d ',' -f2 file1.txt`  
newnum=`expr $oldnum + 1`
sed -i 's\$oldnum\$newnum\g' file1.txt  

But I get an error from sed syntax, is there any way for this. Thanks in advance.

6 Answers

Another, single line, way would be expr cat /tmp/file 2>/dev/null + 1 >/tmp/file

this works if the file doesn't exist or if the file doesnt contain a valid number - in both cases the file is (re)created with a value of 1

Bash one liner option with BC. Sample:

$ echo 3 > test
$ echo 1 + $(<test) | bc > test
$ cat test
4

Also works:

bc <<< "1 + $(<test)" > test
Related