Printing the last column of a line in a file

喜夏-厌秋 提交于 2019-11-28 15:37:22

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
Gennadiy Zolotaryov

To print the last column of a line just use $(NF):

awk '{print $(NF)}' 
miono

You can do this without awk with just some pipes.

tac file | grep -m1 A1 | rev | cut -d' ' -f1 | rev

One way using awk:

tail -f file.txt | awk '/A1/ { print $NF }'
hgh

maybe this works?

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

You can do all of it in awk:

<file awk '$1 ~ /A1/ {m=$NF} END {print m}'
Aziz

Execute this on the file:

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

and you'll get what you're looking for.

JimBob

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.

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

$

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!