swapneil
swapneil

Reputation: 53

How to increment a column value with an increasing number in a csv file

I have a text file with 3 columns as below.

$ cat test.txt
1,A,300
1,B,300
1,C,300

Till now i have tried as, awk -F, '{$3=$3+1;print}' OFS=, test.txt

But output is coming as:

1,A,301
1,B,301
1,C,301

& below is my desired output

Now i want to increment the third column only, the output should be like below

1,A,300
1,B,301
1,C,302

How can I achieve the desired output?

Upvotes: 5

Views: 12052

Answers (5)

P....
P....

Reputation: 18371

 awk 'BEGIN{x=0;FS=OFS=","} NF>1{$3=$3+x;x++}1' inputfile
1,A,300

1,B,301

1,C,302

Explanation:

BEGIN Block : It contains x which is a counter initially set to zero, FS and OFS . /./ is used to ignore blank lines(Remove this part if there are no blank lines). $3=$3+x : This will add the value of counter to $3. x++ : To increment the current value of the counter.

Upvotes: 2

Ramya
Ramya

Reputation: 1

awk 'BEGIN{i=0;FS=OFS=","} NF>1{$3=$3+i;i++}1' filename

It contains x which is a counter initially set to zero, FS and OFS . /./ is used to ignore blank lines(Remove this part if there are no blank lines).

$3=$3+i : This will add the value of counter to $3. i++ : To increment the value of counter. Must and should give space betwen awk and begin as well as filename and end of the file

Upvotes: -1

NeronLeVelu
NeronLeVelu

Reputation: 10039

could be, assuming line are sequential like your sample)

awk -F ',' '{sub($3"$",$3+NR-1)}7' YourFile

it use the line numer as increment value, changing the line end and not the field value (different from an awk POV, that don't need to rebuild the line with separator)

Alternative if empty or other line between modifiable lines (i arbitrary use NF as filter but it depend of your criteria if any)

awk -F ',' 'NF{sub($3"$",$3+i++)}7' YourFile

Upvotes: 3

James Brown
James Brown

Reputation: 37404

Yet another:

awk 'BEGIN{ FS=OFS="," } ($3+=i++)||1 ' file

Upvotes: 0

Mitesh Pant
Mitesh Pant

Reputation: 542

try this NR starts at 1 so NR -1 should give you the correct number

 awk -F, '{$3=$3+NR-1;print}' OFS=, test.txt

Upvotes: 0

Related Questions