I have a file that is constantly being written to/updated. I want to find the last line containing a particular word, then print the last column of that line.
The file looks something like this. More A1/B1/C1 lines will be appended to it over time.
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 a way to do this?
You don't see anything, because of buffering. The output is shown, when there are enough lines or end of file is reached. tail -f
means wait for more input, but there are no more lines in file
and so the pipe to grep
is never closed.
If you omit -f
from tail
the output is shown immediately:
tail file | grep A1 | awk '{print $NF}'
@EdMorton is right of course. Awk can search for A1
as well, which shortens the command line to
tail file | awk '/A1/ {print $NF}'
or without tail, showing the last column of all lines containing A1
awk '/A1/ {print $NF}' file
Thanks to @MitchellTracy's comment, tail
might miss the record containing A1
and thus you get no output at all. This may be solved by switching tail
and awk
, searching first through the file and only then show the last line:
awk '/A1/ {print $NF}' file | tail -n1
要打印一行的最后一列,只需使用 $(NF):
awk '{print $(NF)}'
使用awk
一种方法:
tail -f file.txt | awk '/A1/ { print $NF }'
你可以在没有 awk 的情况下使用一些管道来做到这一点。
tac file | grep -m1 A1 | rev | cut -d' ' -f1 | rev
也许这有效?
grep A1 file | tail -1 | awk '{print $NF}'
您可以在awk
完成所有操作:
<file awk '$1 ~ /A1/ {m=$NF} END {print m}'
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
$
awk -F " " '($1=="A1") {print $NF}' FILE | tail -n 1
Use awk
with field separator -F set to a space " ".
Use the pattern $1=="A1"
and action {print $NF}
, this will print the last field in every record where the first field is "A1". Pipe the result into tail and use the -n 1
option to only show the last line.
Not the actual issue here, but might help some one: I was doing awk "{print $NF}"
, note the wrong quotes. Should be awk '{print $NF}'
, so that the shell doesn't expand $NF
.
Execute this on the file:
awk 'ORS=NR%3?" ":"\n"' filename
and you'll get what you're looking for.
ls -l | awk '{print $9}' | tail -n1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.