Get the nth word of mth line in a file

Hi..

May be a simple question but I just began to write unix scripts a week ago, for sorting some huge amount of experiment data, so I got no common sense about unix scripting and really need your helps...

The situation is, I want to read the nth word of mth line in a file, and then store it in a variable. Been searching through the internet and I got an AWK command like this

var=$(awk "NR==$m{print $1}" input_file)

With this command line above I want to get the first word in line '$m', but it returns the whole line into the $var (words in the file are separated by tab)

In addition, I would need a command to get the '$n'th word in the '$m'th line, but I guess the command below would not work because the wrong formating of '$'

var=$(awk "NR==$m{print $n}" input_file)

Thank you...

Use awk variables. Assuming $n and $m are shell variables:

var=$(awk -v line="$m" -v field="$n" 'NR==line{print $field}' input_file)
1 Like

The avobe explanation is correct, for delimeter in awk use -F and use the value of "nth" filed. For runtime variable assing that variable also. using -v option.

 awk -vvar=5 -F" " 'NR==10 {print $var}' input_file
1 Like

Thank you, the script now runs perfectly !

And the hints of -F option must be useful for basic users like me.