How to select a given column from a line of text?
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 开发者_如何学PythonI 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.
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.
you can use either cut
, awk
, etc.
Example:
awk '{print $3}' my_file.txt
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
精彩评论