0

I did a recursive grep in a directory to find all files that would match as follows

grep -ER "match_string1|match_string2" /path/to/dir/

What I get as output is:

/path/to/dir/timestamp.log:match_string1
/path/to/dir/timestamp.log:match_string2
/path/to/dir/timestamp.log:match_string2

Where match_string1 represents a model# Where match_string2 represents a test result

I would like to merge the lines so that I can say when model# and test result match specific criteria then count

Note: It is fine to have double match_string2 on the same line as match_string1

Example output I would expect:

/path/to/dir/timestamp.log:match_string1; /path/to/dir/timestamp.log:match_string2; /path/to/dir/timestamp.log:match_string2

Appreciate the help

  • In above example you want to double match_string2 in one line with match_string1 or not? Or may be better to show the finish purpose what you'd like to calculate? – Costas May 1 '15 at 18:18
  • Your question is not clear. When you say "match_string1 is x", what do you mean by "is x"? And what do you want on the same line? Note that grep outputs the entire line that matches, not just the pattern. – Bjorn Munch May 1 '15 at 18:21
  • Bjorn I updated the question to be a little more clear – rainereality May 1 '15 at 18:30
2
sed '/match_string1/{
     :1
     N
     /\n.*match_string2/s/\n/; /
     t1
     P
     D
                     }'

When script met line with match_string1 it add next line to pattern and check if in that added line there is match_string2 if so they substitute newline sign by ; and add next line to check. If there is not match_string2 (so substitution haven't made) the script prints first line and start process from beginning with second line.

  • Which part of the sed script is the part that defines whether or not to check the next line? Where is it making the decision whether or not to keep looking for the match in the next line? – rainereality May 1 '15 at 18:51
  • @rainereality If in line meet match_string1 script adds next line and check it for match_string2 presence – Costas May 1 '15 at 19:03
  • What arguments are doing that is that the :1 or the N? I don't understand the purpose of the t1, the P and the D either. – rainereality May 1 '15 at 19:06
  • This is /match_string1/. N add next line, t1 return script to :1 position only if previous substitution by s is succeed. P prints first line (may be long with all added match_string2), D delete ones and return to the begin and process the second line which remains in memory (pattern space) – Costas May 1 '15 at 19:12
  • you're awesome! know anywhere that has some good example usage of sed functions so I can familiarize myself more with sed conditions and functions? – rainereality May 1 '15 at 19:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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