Added word expansion

I have a large text file where the word DATA appears more than 10,000 times. I would like to know how to make a conditional change, so when it first appears in the document, it changes to NO1, and the second time to NO2, etc. Using bash. I was thinking of some kind of complex script using bash, but there probably should be a simpler way.

+3
source share
2 answers
perl -pe 's/DATA/ "NO" . ++$n /ge' file_in > file_out
+5
source
 awk '{
     for (i=1;i<=NF;i++) { 
          if ($i == "DATA") printf("%s%s", "NO"++n, OFS); 
           else  printf("%s%s", $i, OFS)      
          if (i==NF) printf "\n"
     }      
  }' file > outFile

OR, as Glenn Jackman rightly points out, this can be collapsed to

awk '{for (i=1; i<=NF; i++) if ($i=="DATA") $i = "NO" ++n} {print}' file > outFile

I leave my original version in place to show an alternative (but overloaded) approach; -)

Hope this helps.

+1
source

All Articles