Naveen Reddy CH
Naveen Reddy CH

Reputation: 839

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.

Upvotes: 16

Views: 42765

Answers (6)

ScottG
ScottG

Reputation: 71

Another one-liner would be:

$ expr `cat /tmp/file 2>/dev/null` + 1 >/tmp/file

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

Upvotes: 7

Jotne
Jotne

Reputation: 41456

Here is how to do it with awk

awk -F, '{$2=$2+1}1' OFS=, file1.txt
2013-12-29,2

or more simply (this will file if value is -1)

awk -F, '$2=$2+1' OFS=, file1.txt

To make a change to the change to the file, save it somewhere else (tmp in the example below) and then move it back to the original name:

awk -F, '{$2=$2+1}1' OFS=, file1.txt >tmp && mv tmp file1.txt

Or using GNU awk, you can do this to skip temp file:

awk -i include -F, '{$2=$2+1}1' OFS=, file1.txt

Upvotes: 4

BoeroBoy
BoeroBoy

Reputation: 1200

Bash one liner option with BC. Sample:

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

Also works:

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

Upvotes: 2

michaeltang
michaeltang

Reputation: 2898

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

Upvotes: 8

ray
ray

Reputation: 4267

awk is the best for your problem, but you can also do the calculation in shell

In case you have more than one rows, I am using loop here

#!/bin/bash
IFS=,
while read DATE NUM
do
echo $DATE,$((NUM+1))
done < file1.txt

Upvotes: 0

Wes Hardaker
Wes Hardaker

Reputation: 22262

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.

Upvotes: 24

Related Questions