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


Now I want the file to be

// basically subtract 1 from all 

What I have tried so far is

$awk '{if(getline != 0){
          for(i = 0; i <=NF; i++){
       } 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.


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

awk -vOFS=, -F, '{
      for(i = 1; i <=NF; i++ ){
          $i -= 1;
   }' 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.