# Print first element of the last line of files when the second element does not match a pattern

I am relatively new to Bash, regular expression and stuff.

In a directory, I need to read the last line of all the files that contain the word "fitness", and list (on one line and separated with comas) the first element of these last lines (where elements are defined by spaces), whenever the second element (or any element actually) is not "100000".

tail -n 1 *fitness* | grep -v '100000' | grep -v 'fitness' | awk '{print $1}' | grep -v '^$' | paste -d  "," - - - - - - - - - - - - - - - - -


In words:

read all last lines | don't consider those that contain the number 100000 | remove the name of the files | take the first element | remove blank lines | paste the element together on one line separated by comas

Can you help me to improve my code?

• Should '100000' appear anywhere, or does it need to be an entire word on its own? For example, if the last line includes '100000000' or 'foo100000bar', should the first field be printed? – erichamion Aug 13 '15 at 1:19

That second grep (grep -v 'fitness') is there to filter out the filenames that tail spits out, right? That can be removed by using the -q option for tail.

Personally, I'd try to avoid that paste command, but that might just be because I'm not used to it. If you don't need spaces after the commas, tr works just fine.

tail -qn 1 *fitness* | grep -v '100000' | awk '{print $1}' | grep -v '^$' | tr '\n' ','


Now, since you're already using awk, why not do a bit more with it (actually, the whole thing could probably be made into an awk program with either more time or more experience than I have available)?

This uses a single awk statement to choose only lines that don't contain the word '100000' and also have a non-empty first field, and also to print that first field. What it does for readability depends on personal preference, but it certainly reduces the number of programs that need to be chained together:

tail -qn 1 *fitness* | awk '(! /\<100000\>/) && $1 !~ /^$/ {print \$1}' | tr '\n' ','