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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With