Codeme
Codeme

Reputation: 147

Use cut in shell to extract last word

I am using Red Hat linux.

I have a file foo.txt which reads

Hello world I am foo

I want to get the last word which is foo when I do cat

I tried seeing a few posts here which explained to use cut command but its very confusing. Can somebody help me getting this right?

I am looking for a command which migh go something like below

cat foo.txt | cut <the options to get the last word /or last 3 characters>

Upvotes: 1

Views: 8387

Answers (5)

glenn jackman
glenn jackman

Reputation: 247210

GNU grep using a PCRE to get the characters following the last whitespace in the line (or following the start of line if there is no whitespace):

grep -oP '(.*\s|^)\K.+' file

Upvotes: 0

MasterDevX
MasterDevX

Reputation: 23

If using cat is necessary, you can try this:

cat foo.txt | rev | cut -d ' ' -f 1 | rev

Explanation:
cat will pipe contents of foo.txt file to the rev command. So, rev will receive:

Hello world I am foo

and will invert it:

oof ma I dlrow olleH

Then cut eill extract the first word of inverted string:

oof

Here -d ' ' means that space character is delimiter used to split your string by several fields, and -f 1 means you are taking the first field.

Finally, rev is used once again to invert extracted word again, so yo will get:

foo

Upvotes: 0

scriptboy
scriptboy

Reputation: 856

As @choroba mentioned, cut can't do that.

A simple way to that is to use awk.

cat foo.txt | awk '{print $(NF)}'

NF is the number of fields in the current record. So the $(NF) would be the last word.

Upvotes: 2

choroba
choroba

Reputation: 242343

cut can't count from the right. But you can use rev to reverse each line, than count from the left normally, and revert the line back. It's still surprisingly fast.

rev foo.txt | cut -d' ' -f1 | rev
  • -d specifies the delimiter, I guess you want spaces when counting words
  • -f specifies which field(s) to extract. Use -c to extract individual characters.

Upvotes: 8

zanko
zanko

Reputation: 41

with -n [number of lines] you can limit number of lines. use -c to limit count of characters

Upvotes: 0

Related Questions