1
\$\begingroup\$

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?

asked Aug 12, 2015 at 18:35
\$\endgroup\$
1
  • \$\begingroup\$ 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? \$\endgroup\$ Commented Aug 13, 2015 at 1:19

1 Answer 1

2
\$\begingroup\$

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' ','
answered Aug 13, 2015 at 1:48
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.