vyasap
vyasap

Reputation: 1

NF in an awk function

I have a file in which i have mobile numbers and their categories. Not all the mobile number are having category available.for example

mobile123456678
category1
mobile345968483
category2
mobile956868483
mobile958688504
mobile958688438
mobile058684838
category4
mobile238348459
category5
mobile958584939
category6

etc.etc

so i have used below awk command and it gave the the mobile numbers for which category is available. but i am not able to understand how it worked

cat file | awk '{if ($0~/mobile/) {k=$NF;l=($NF-1)} else {print k,$0}}'

.

mobile123456678 category1
mobile345968483 category2
mobile058684838 category4

etc

pls let me know how this worked.

Upvotes: 0

Views: 224

Answers (1)

fedorqui
fedorqui

Reputation: 290105

If you are willing to print those lines whose next line is not on the form mobileXXX, you can directly say:

$ awk '/^mobile/ {m=$NF; next} {print m, $0}' file
mobile123456678 category1
mobile345968483 category2
mobile058684838 category4
mobile238348459 category5
mobile958584939 category6

This checks if a line starts with the text mobile and, if so, stores in a variable m the mobile value (last field $NF*, as per your input and code, although it could also be $0 in this case). Then, it moves to the next record.

If the line did not start with mobile, it prints the previously stored mobile together with the current line.

What I just suggested is a more idiomatic way to write what you had:

awk '{if ($0~/mobile/) {k=$NF;l=($NF-1)} else {print k,$0}}' file

Because the if () {action} else {else_action} can be avoided by saying condition {action; next} {else_action}.


* $NF refers to the last field in a given record, since NF stands for number of fields and $n for the n-th field.

Upvotes: 1

Related Questions