1

As for this Command:

awk '{for(x=1;x<=NF;x++)if($x~/0.00000/){sub(/0.00000/,++i)}}1'

I know this command will look for "0.00000" in a file and replace it with an incremental number starting from 1. I understood almost everything except for 'x<=NF' and the number 1 at the end "{sub(/0.00000/,++i)}}1'. Can you enlighten me on these two points, please?

Also, If I want to do the same thing but replacing the match with an incremental number starting from 0, would it be correct to do:

awk '{for(x=0;x<=NF;x++)if($x~/0.00000/){sub(/0.00000/,++i)}}1' file
FZJ
  • 113

2 Answers2

4

NF is an internal Awk variable whose value is set to the number of fields in the current record. So

for(x=1;x<=NF;x++)

is looping over all the fields. The number 1 at the end of the expression is a shorthand way of printing the whole record, making use of the default action when a pattern evaluates "true":

In an awk rule, either the pattern or the action can be omitted, but not both. If the pattern is omitted, then the action is performed for every input line. If the action is omitted, the default action is to print all lines that match the pattern.1

To start the incrementing number from 0 instead of 1, you can replace the prefix ++i by postfix i++:

awk '{for(x=1;x<=NF;x++)if($x~/0.00000/){sub(/0.00000/,i++)}}1'

ex.

$ echo 'foo 0.00000123 bar' | awk '{for(x=1;x<=NF;x++)if($x~/0.00000/){sub(/0.00000/,++i)}}1'
foo 1123 bar

whereas

$ echo 'foo 0.00000123 bar' | awk '{for(x=1;x<=NF;x++)if($x~/0.00000/){sub(/0.00000/,i++)}}1'
foo 0123 bar
$

  1. The GNU Awk User's Guide: 1.3 Some Simple Examples
steeldriver
  • 81,074
  • Thank you for the explanation. For the second part of my question, I would like to start the incrementing number from 0 like 0, 1, 2,...6000 and not from 1 to 0. Is it correct what I proposed? – FZJ Oct 11 '18 at 19:37
  • @FZJ no, what you proposed would apply the search-and-replace operation to the whole record ($0) in addition to each individual field ($1 to $NF) – steeldriver Oct 11 '18 at 19:39
  • Ah, I see. In this case, how can I start the incrementation from 0, please? – FZJ Oct 11 '18 at 19:46
  • for(x=0 and so forth. That is where the start of the loop is defined. – DopeGhoti Oct 11 '18 at 19:49
  • Regarding the 1 answer here: https://unix.stackexchange.com/questions/63891/what-is-the-meaning-of-1-at-the-end-of-awk-script – Roland Apr 06 '20 at 09:11
0

It may be worth to mention that

sub(/0.00000/,i++)

will replace the first occurrence in the entire line ($0, the default). By accident, this will also be the occurrence in $x. To make it failsafe, and for future application, replace it with

sub(/0.00000/,i++, $x)
RudiC
  • 8,969