Can a shell script pull the first word (or nth word) off each line of a text file?

Greetings.

I am struggling with a shell script to make my life simpler, with a number of practical ways in which it could be used. I want to take a standard text file, and pull the 'n'th word from each line such as the first word from a text file.

I'm struggling to see how each line can be treated differently, and captured as a variable.

If I try using the for n in `cat filename` approach, it simply takes each word from the filename.

And since the file may have multiple lines, I want to use a text file as the basis for a shell script, using variables taken from the file on a line by line basis.

Is there a simple way? Searching google and other search engines pulls up too many read herrings or inappropriate pages.

Can anyone please help?
:rolleyes:

for n in `cat filename` will also read all words into $n if you change the IFS variable to newlines only.

So if I understand it, you might have a file like this:
--- filename ---
file1 10
file2 20
file3 30
file4 40
---------------

Say I want to get the word count of each file and print next to it the corresponding 10, 20, 30, or 40..
~$ cat filename | while read line; do x=`echo $line | awk '{print $1}'`; y=`echo $line | awk '{print $2}'`; echo `wc -l $x` $y; done

6 file1 10
46 file2 20
8 file3 30
87 file4 40

Another way uses awk:

~$ cat filename | while read line; do a=`echo $line | awk '{print "b="$1,"c="$2}'`; eval $a; echo `wc -l $b` $c;done

I'll give that thought a try and post the complete script.....

the first word ? assuming hat is word are space separated you can use 'cut'

cut -d\ -f1 <file

please note the are 2 space after the \ 1. as argument 2. as separator

#!/bin/ksh
filename="$1"
n=$2
awk -v fld=$n '{if(NF>=fld) {print $fld} } ' "$filename"