prathmesh.kallurkar
prathmesh.kallurkar

Reputation: 5686

grep and sed to capture parameter in file

I have a line which has some parameters that I want to grab. What is the best way to do this?

Example line is :

l1_user_instr hits=0035191479 misses=0000013657
l1_user_data hits=0009562889 misses=0001215170

I want to write a script which gives hits=xx and miss=yy for a particular configuration.

grep l1_user_instr_hits | sed ?

I am not an expert in sed and hence the question.

Upvotes: 0

Views: 248

Answers (4)

William Pursell
William Pursell

Reputation: 212454

It's not entirely clear what you are looking for, but judging from comments in other answers I think you want the ability to get either the number of hits or the number of misses, and nothing else. For example, when looking for hits on configuration 'l1_user_data', you want the output to be exactly:

0009562889

An easy thing to do (you could add a better interface) would be something like:

awk -v f=3 -v c=l1_user_instr -F ' *|=' '$0 ~ c {print $f}' input

By setting FS to split the line on = as well as white space, we've made the number of hits field 3, and the number of misses is field 5. Set the variable c to the string you want to match, and set f to the field you want to display (either 3 or 5). Note that you might want to handle tabs as well as spaces in FS (there are a lot of things that could/should be done to improve this interface, but for a one-off, this is fine).

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 360355

while IFS=" =" read -r type _ hits _ misses
do
    echo "Type: $type, Hits: $hits, Misses: $misses"
done < inputfile

Example output:

Type: l1_user_instr, Hits: 0035191479, Misses: 0000013657
Type: l1_user_data, Hits: 0009562889, Misses: 0001215170

Upvotes: 1

Zsolt Botykai
Zsolt Botykai

Reputation: 51653

With sed (if I get correctly what you want):

sed '/l1_user_instr/ s/.*\(hits=\d\+\) \(misses=\d\+\)[^0-9]*$/\1\n\2/;q' INPUTFILE

Basically it will search for matching l1_user_instr line, and on that line creates two groups for matching the required data, then prints them new line separated, and exits. The awk solution is simmilar:

awk '/l1_user_instr/ {printf("%s\n%s\n",$2,$3) ; exit}' INPUTFILE

Upvotes: 1

Steve
Steve

Reputation: 54532

Perhaps awk would suit your needs. Try this:

awk '/l1_user_instr/ { print $2,$3 }' file.txt

Results:

hits=0035191479 misses=0000013657

HTH

Upvotes: 1

Related Questions