10

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
0
28

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.

4

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
2
  • 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 '14 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 '14 at 11:05
4

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
4

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

while read -a fields; do
    echo ${fields[-1]}
done < file
2

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

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