Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing first word in every line of a txt file unix bash

Tags:

file

bash

unix

So I'm trying to print the first word in each line of a txt file. The words are separated by one blank.

cut -c 1 txt file  

Thats the code I have so far but it only prints the first character of each line. Thanks

like image 735
ap1993 Avatar asked Oct 02 '13 19:10

ap1993


People also ask

How do you find the first word of a line in Unix?

In case your string contains newlines | head -n1 will select the first line first before the important commands select the first word from the string passed to it. The would return the first word of every line, not the first word.

How do I print the first word in Linux?

To print a whole word, you want -f 1 , not -c 1 . And since the default field delimiter is TAB rather than SPACE, you need to use the -d option.

How do you get extract a word from a line in Bash shell script?

If "name=foo" is always in the same position in the line you could simply use: awk '{print($3)}' , that will extract the third word in your line which is name=foo in your case. He told "also other parameters may or may not be there" hence you may not use a positional logic.

How do I get the first element of a string in Bash?

Getting the first character To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell.


1 Answers

To print a whole word, you want -f 1, not -c 1. And since the default field delimiter is TAB rather than SPACE, you need to use the -d option.

cut -d' ' -f1 filename 

To print the last two words not possible with cut, AFAIK, because it can only count from the beginning of the line. Use awk instead:

awk '{print $(NF-1), $NF;}' filename 
like image 162
Barmar Avatar answered Oct 23 '22 12:10

Barmar