views:

42

answers:

3

Suppose I have this sentence:

My name is bob.

And I want to copy the word "is" from that sentence into a variable. How would I access that word, without knowing in advance the word I am looking for? If I know a specific word or string is in the third column of text in a five column text line, how can I take the word in the third column?

I'm using the bourne shell.

+3  A: 
word=$(cut -d ' ' -f 3 filename)

cut gives us the third field of each line (in this case there's 1). -d is used to specify space as a delimiter. $() captures the output, then we assign it to the word variable.

Matthew Flaschen
I don't believe tail is required from what the OP meant, the leading line of numbers (now removed) was spaced out to indicate columns rather than being content.
Roger Pate
@Roger, I think you're right. I've updated it.
Matthew Flaschen
+1  A: 

Hello, you can use either cut, awk, etc.

Example:

awk '{print $3}' my_file.txt
Benoit
A: 
sentence='My name is bob.'
set -- $sentence
echo $3

or

sentence='My name is bob.'
set -- $sentence
shift 2    # or use a variable
echo $1
Dennis Williamson