Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment number in a file

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.

like image 310
Naveen Reddy CH Avatar asked Dec 30 '13 08:12

Naveen Reddy CH


2 Answers

Sed needs forward slashes, not back slashes. There are multiple interesting issues with your use of '\'s actually, but the quick fix should be (use double quotes too, as you see below):

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

However, I question whether sed is really the right tool for the job in this case. A more complete single tool ranging from awk to perl to python might work better in the long run.

Note that I used a $ end-of-line match to ensure you didn't replace 2012 with 2022, which I don't think you wanted.

like image 66
Wes Hardaker Avatar answered Sep 28 '22 18:09

Wes Hardaker


usually I would like to use awk to do jobs like this following is the code might work

awk -F',' '{printf("%s\t%d\n",$1,$2+1)}' file1.txt
like image 41
michaeltang Avatar answered Sep 28 '22 17:09

michaeltang