shans91
shans91

Reputation: 29

Awk command to insert corresponding line numbers except for blank lines

I'm doing an assignment at the moment and the question that's stumped me is:

"Write an awk command to insert the corresponding line number before each line in the text file above. The blank line should NOT be numbered in this case."

I have an answer, but I'm struggling to find the explanation of what each component does.

The command is:

awk '{print (NF? ++a " " :"") $0}' <textfile.txt>

I know that NF is the field number, and that $0 refers to the whole input record. I tried playing around with the command to find what does what, but it always seems to have syntax errors whenever I omit something.

So, my question is what does each component do? What does the ++a do? The ? after NF? and what does the bit with the quotations do?

Thanks in advance!

Upvotes: 1

Views: 1614

Answers (2)

Vijay
Vijay

Reputation: 67291

print (NF? ++a " " :"") $0

a ternary operator has been used in your solution. for a blank line NF will be 0 always so

cond?true case:false case

if NF is >0 then print a or else print "" a++ says that after printing increment a by 1 which will be used for next non blank line processing.

awk 'BEGIN{count=1}{if($0~/^$/){print}else{print count,$0;count++}}' your_file

tested below:

> cat temp.cc
int main ()
{

}
> awk 'BEGIN{count=1}{if($0~/^$/){print}else{print count,$0;count++}}' temp.cc
1 int main ()
2 {

3 }
> 

Upvotes: 0

Birei
Birei

Reputation: 36272

The instruction ... ? ... : ... it's an if-else. So, it's the same as:

if ( NF > 0 ) {
    ++a;
    print a " " $0;
} else {
    print $0;
}

a is a variable that is only incremented when found a line with fields.

Upvotes: 1

Related Questions