Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing the last column of a line in a file

Tags:

file

tail

awk

People also ask

What is the command to print the last line of a file?

tail [OPTION]... [ Tail is a command which prints the last few number of lines (10 lines by default) of a certain file, then terminates.

How do I print the last column in Unix?

“awk” is a very powerful Linux command that can be used with other commands as well as with other variables. This command is essentially used to read the content of a file.

Which command is used to extract the last field from a file?

The cut command in UNIX is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text.


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

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

awk '{print $(NF)}' 

One way using awk:

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

You can do this without awk with just some pipes.

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

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}'