Print the last column of a row in a file

I have a file that is constantly being written to / updated. I want to find the last row containing a specific word, then print the last column of that row.

The file looks something like this. Over time, additional lines A1 / B1 / C1 will be added.

A1 123 456 B1 234 567 C1 345 678 A1 098 766 B1 987 6545 C1 876 5434 

I tried to use

 tail -f file | grep A1 | awk '{print $NF}' 

to print the value 766 but nothing is output.

Is there any way to do this?

+90
file awk tail
Oct 24 '12 at 9:13
source share
11 answers

You do not see anything due to buffering. The output is displayed when there are enough lines or the end of the file is reached. tail -f means waiting for more input, but there are no more lines in file , and therefore the channel to grep never closes.

If you omit -f from tail output will be shown immediately:

 tail file | grep A1 | awk '{print $NF}' 



@Edmorton is, of course, right. Awk can also search for A1 , which shortens the command line to

 tail file | awk '/A1/ {print $NF}' 

or without tail, showing the last column of all rows containing A1

 awk '/A1/ {print $NF}' file 



Thanks to the comment, @MitchellTracy tail can skip a record containing A1 and thus, you won’t get anything at all. This problem can be solved by switching tail and awk , awk search first in the file, and then showing the last line:

 awk '/A1/ {print $NF}' file | tail -n1 
+144
Oct 24 '12 at 9:17
source share

To print the last column of a row, simply use $ (NF):

 awk '{print $(NF)}' 
+11
Apr 05 '17 at 20:20
source share

You can do this without awk with just a few pipes.

 tac file | grep -m1 A1 | rev | cut -d' ' -f1 | rev 
+10
Oct 24
source share

One way: awk :

 tail -f file.txt | awk '/A1/ { print $NF }' 
+8
Oct 24 '12 at 10:13
source share

Maybe it works?

 grep A1 file | tail -1 | awk '{print $NF}' 
+1
Oct 24 '12 at 9:19
source share

You can do it all in awk :

 <file awk '$1 ~ /A1/ {m=$NF} END {print m}' 
+1
Oct 24 '12 at 10:29
source share

Run this in the file:

 awk 'ORS=NR%3?" ":"\n"' filename 

and you get what you are looking for.

0
Jan 31 '13 at 17:14
source share
  grep A1 aaa.txt|tail -1|awk '{print $NF}' 
0
Jul 10 '14 at 8:16
source share

ls -l | awk '{print $9}' | tail -n1

0
Feb 23 '17 at 19:38
source share

awk -F " " '($1=="A1") {print $NF}' FILE | tail -n 1

Use awk with the -F field separator set to space "".

Use the template $1=="A1" and the action {print $NF} , this will print the last field in each record, where the first field is "A1". -n 1 result in tail and use the -n 1 option to show only the last line.

0
Dec 04 '18 at 14:14
source share

Using Perl

 $ cat rayne.txt A1 123 456 B1 234 567 C1 345 678 A1 098 766 B1 987 6545 C1 876 5434 $ perl -lane ' /A1/ and $x=$F[2] ; END { print "$x" } ' rayne.txt 766 $ 
0
Feb 09 '19 at 14:08
source share



All Articles