Printing the last column of a line in a file

前端 未结 11 1442
遇见更好的自我
遇见更好的自我 2020-12-12 11:33

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 fi

相关标签:
11条回答
  • 2020-12-12 12:31

    Execute this on the file:

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

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

    0 讨论(0)
  • 2020-12-12 12:32

    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
    
    0 讨论(0)
  • 2020-12-12 12:35

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

    0 讨论(0)
  • 2020-12-12 12:36

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

    awk '{print $(NF)}' 
    
    0 讨论(0)
  • 2020-12-12 12:38

    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.

    0 讨论(0)
提交回复
热议问题