assign values from awk output - help

Dear All,

I have a command which gives the number of fields of each line of a comma-separated file.

sthng like this :
cat QDB_20071126_002.bad | awk -F"," '{ print NF }'

I need to assign the first output and the last output of the above command to variables in a script.
Need help to do that.

Thanks in advance.

set -- `awk -F, 'NR==1 { print $NF; next } { last=$NF } END { print last }' QDB_20071126_002.bad`
firstvariable=$1
lastvariable=$2

You could do it with two separate awk invocations or something, but the above is more efficient (although somewhat obscure, the set -- `command` trick is a standard shell programming idiom).

Hi,

Thanks for your quick reply.
Your command actually prints the last field of first and last line, whereas what i need is the number of fields of first and last line, to be assigned to variables.

Lines are comma-separated.

The below command prints number of fields of each line of the comma-separated file:
cat QDB_20071126_002.bad | awk -F"," '{ print NF }'

6
7
7
7
2

I need to take '6' and '2' and assign it later.
Help me out on this..

Thanks in advance.

Sorry, my bad, just remove the dollar signs before NF in both places; sorry for missing that.

By the by, awk can read the file all by itself; no need to invoke a separate cat for that.

you can assign variables back to the shell using set as era has mentioned

set -- `awk 'NR==1{print NF}END{print NF}' file`

or just do whatever you need to do in awk itself

awk 'NR==1{first=NF}END{ 
   print NF #do something.
   print f # do something
}' file