0

This question already has an answer here:

How can I sub 1 from each element from my txt file. I had actually tried similar to this question but was not successes full.

Suppose I have file in the following format

2,4,5
1,2,3
14,12,1

Now I want the file to be

// basically subtract 1 from all 
1,3,4
0,1,2  
13,11,0

What I have tried so far is

$awk '{if(getline != 0){
          for(i = 0; i <=NF; i++){
              $(i)=$(i)-1;
          }
       } print;}}'

I was trying to read till end of file and sub 1 from each element, but when I do this I just -1

marked as duplicate by jasonwryan, sam, Eric Renouf, Jeff Schaller, Kaz Nov 29 '16 at 1:19

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

The logic is right - but you've made a couple of errors:

awk -vOFS=, -F, '{
      for(i = 1; i <=NF; i++ ){
          $i -= 1;
      }
      print;
   }' file.txt
  • getline (as you've used it) reads the next line into $0 - it doesn't make sense here.

  • You need to tell awk to split (FS or using -F) on a comma, by default it will split on whitespace

  • $0 is the whole line so you want to start your loop at i = 1

  • If you want to print commas on the output you need to set OFS=, (output field separator).

Alternatively you can use perl:

perl -ple 's{(\d+)}{$1 - 1}eg;' file.txt

Not the answer you're looking for? Browse other questions tagged or ask your own question.