Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

shell

unix

sh

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.

like image 570
Waffles Avatar asked Oct 19 '10 06:10

Waffles


People also ask

How do you select a column in a line?

You can also click anywhere in the table column, and then press CTRL+SPACEBAR, or you can click the first cell in the table column, and then press CTRL+SHIFT+DOWN ARROW. Note: Pressing CTRL+SPACEBAR once selects the table column data; pressing CTRL+SPACEBAR twice selects the entire table column.

How do I select a specific column in a text file?

With the cursor just before the first entry of the column, press Ctrl + Alt + Shift + End . This will enlarge the cursor over the full column. Now press Ctrl + Shift + Right and the full column will be selected.

How do I select a column from a certain cell?

Or click on any cell in the column and then press Ctrl + Space. Select the row number to select the entire row. Or click on any cell in the row and then press Shift + Space. To select non-adjacent rows or columns, hold Ctrl and select the row or column numbers.


2 Answers

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.

like image 60
Matthew Flaschen Avatar answered Oct 19 '22 04:10

Matthew Flaschen


you can use either cut, awk, etc.

Example:

awk '{print $3}' my_file.txt
like image 38
Benoit Avatar answered Oct 19 '22 05:10

Benoit