Operating System - HP-UX
1828990 Members
2701 Online
109986 Solutions
New Discussion

select the nth word on a line in an ascii file

 
SOLVED
Go to solution
Franky Leeuwerck
Frequent Advisor

select the nth word on a line in an ascii file

Hello,

What's the easiest way for assigning the wth word of a line l in a textfile t to variable v in a script ?

Franky

7 REPLIES 7
G. Vrijhoeven
Honored Contributor

Re: select the nth word on a line in an ascii file

Hi,

you can use sed or vi:

cat file | sed "/string/$VARIABLE/g"

or use the vi command
:
g/string/s//$VARIABLE/g

hope this will help

Gideon
Frederic Sevestre
Honored Contributor
Solution

Re: select the nth word on a line in an ascii file

Hi,

If you have any word to identified your line, try
V=$(cat FILE | grep WORD | awk '{ print $n }')
where FILE is the textfile's name, and n the position of the word you need.
R
Fr??d??ric
Crime doesn't pay...does that mean that my job is a crime ?
Robin Wakefield
Honored Contributor

Re: select the nth word on a line in an ascii file

Hi Franky,

As a one-liner:

v=`awk 'NR==l{print $w}' w=$w l=$l $t`

or in a script:

================================
#!/bin/ksh

w=$1
l=$2
t=$3
v=`awk 'NR==l{print $w}' w=$w l=$l $t`
echo $v
================================

so if /tmp/file contains:
a b c
d e f
g h ij k
345 234 234

# ./script.sh 3 2 /tmp/file
h

Rgds, Robin
Volker Borowski
Honored Contributor

Re: select the nth word on a line in an ascii file

Try

v=`echo $LINE | cut -f 67`

assuming you transfered the text-line in charge to the variable LINE and the word you want is word 67 and you consider a "word" as whitespace-delimited as usual in C.

Hope this helps
Volker
Marcin Wicinski
Trusted Contributor

Re: select the nth word on a line in an ascii file

Hi,

best way is to grep line and select required word with awk '{ print $n }'.

Later,
Marcin Wicinski
Volker Borowski
Honored Contributor

Re: select the nth word on a line in an ascii file

Hi again,

if you want to process an entire file, here is another aproach, which should no even be limited to a max of 199 words per line as an awk solution:

#!/usr/bin/sh
# Set Word to be processed -1
WTH=3
assign()
{
if [ $# -ge $WTH ]
then
shift $WTH
WORD=$1
else
WORD=''
fi
}

while read LINE
do
assign $LINE
# now $WORD contains the word in charde
v=$WORD

# Do whatever you want with $v
echo processing: $v

done




Works like:

# sh procline.sh

a b c d e f
processing: d
one two three four five
processing: four
a b c d e f g h
processing: d
a
processing:
#

I like these puzzles
Volker
Franky Leeuwerck
Frequent Advisor

Re: select the nth word on a line in an ascii file

Thanks everyone !
The solutions that suits me best is the one with the grep - awk combination.

Regards,
Franky