Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can one print the element after the last tab in a file?

Exemple: File1

A    3    8    6    7
B    4    6    2    3    6    8
c    1    9

would return:

7
8
9
share|improve this question

5 Answers 5

up vote 13 down vote accepted

You can make smart use of the NF variable in awk

awk '{print $NF}' File1

From man awk

NF The number of fields in the current input record.

So NF will give you the amount of fields and $NF will then expand to $3 for example, which you can use in a print statement.

share|improve this answer

If you want the last field only and not both first and last, you could try:

rev file | cut -f 1

The rev reverses each line of the file and the cut prints only the first field (fields are defined by tabs by default). Since the line has been reversed, the first field is the original last field.

The above works in your given example but, as @Bernhard points out below, it will print fields that are longer than a single character reversed. In those cases, you will need a second rev:

 rev file | cut -f 1 | rev
share|improve this answer
    
If the last field is more than one character, it will be shown in reverse, so you'll need another pipe to rev. –  Bernhard Jul 21 at 11:01
    
@Bernhard d'oh! Of course it will, thanks. Didn't really think of it since I would also use awk for this. I just posted this answer for the sake of completeness. –  terdon Jul 21 at 11:05

You can use sed for such operation:

sed 's/.* //' file # where ' ' -- is your delimiter

It will delete all symbols before the delimiter. If your file is tab-separated, use:

sed 's/.*\t//' file
share|improve this answer

awk is really the tool for the job here but for the sake of completeness here's a GNU grep way

grep -oE '[^[:space:]]+$' file
7
8
9
share|improve this answer

Bernhard's answer is the correct one. For fun and completeness, bash:

while read -a fields; do
    echo ${fields[-1]}
done < file
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.