5

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?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
swapneil
  • 53
  • 1
  • 1
  • 6
  • If any of the following answer helped you in your goal please accept/upvote the answer for closure by ticking right sign besides the answer. – P.... Mar 27 '17 at 11:05

5 Answers5

3

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
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
2
 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.

JohnC
  • 2,687
  • 1
  • 22
  • 30
P....
  • 17,421
  • 2
  • 32
  • 52
  • x=0 could be omitted, its 0 by default if used as adding value for unassigned variable. your `x++` could be directly included in `$3=$3+x++`, and `$3=$3+` could be rewrite with `$3+=`. your /./ is also at risk with space line, use maybe a `NF > 1` or `/[^[:blank:]]/`. Your code is correct, do the job so worth the +1 – NeronLeVelu Feb 02 '17 at 09:45
0

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
Mitesh Pant
  • 524
  • 2
  • 15
0

Yet another:

awk 'BEGIN{ FS=OFS="," } ($3+=i++)||1 ' file
James Brown
  • 36,089
  • 7
  • 43
  • 59
-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

Ramya
  • 1
  • 1
  • Thanks for your contribution, however, the answer is not readable, can you please format it and add more details? – Sid Jan 21 '20 at 05:34