开发者

How to select a given column from a line of text?

开发者 https://www.devze.com 2023-01-20 07:56 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消