Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am trying to extract patterns from cat ing a file in a bash script. I need to extract 10 and 80 line by line. How do I do this?

Total Branch Predictor Mispredictions: 10
Total Branch Predictor OK predictions: 80
share|improve this question

1 Answer 1

up vote 4 down vote accepted
$ cat > data
Total Branch Predictor Mispredictions: 10
Total Branch Predictor OK predictions: 80
$ cat data | awk '{print $NF}'
10
80
$ cat data | awk '{printf "%s ",$NF}'
10 80 $ awk '{printf "%s ",$NF}' < data
10 80 $

awk not only knows $1, $2 etc. to address the n-th column, but also $NF to address the last column (in this case, 10 and 80). The second command utilises printf rather than print to spit out everything in one line (observe the missing newline at the end). The third command avoids using cat.

There is also a solution involving sed:

$ sed 's/^[^:]*: \([0-9]*\)/\1 /' < data
10
80

And one only involving bash:

$ while read line; do printf "%s " "${line##*: }"; done < data; echo
10 80 
$ 

which reads the file line by line, mangles the line variable by deleting the largest matching pattern from the left (in this case: everything up to :) and passing it to printf, which then proceeds to format it. I added echo at the end to get a final newline :)

share|improve this answer
    
I think the OP meant that he wants to see the correlating performance data in one line, like 10 80 (though it's hard to guide somebody when he doesn't specify, where he wants to get) –  ppeterka Oct 21 '12 at 18:36
    
in this case, use cat data | awk '{printf "%s ",$NF}'. –  Claudius Oct 21 '12 at 18:38
    
and, to avoid the useless use of cat, try $ awk '{printf "%s ",$NF}' < data (although the OP explicitly said cat ing). –  Claudius Oct 21 '12 at 18:39
    
I think you should add these bits to the answer, it will be useful for the future Super User dweller... –  ppeterka Oct 21 '12 at 18:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.