0

I have the following problem with a search method in Linux: I want to search multiple strings (e.g. text1, text2 and text3) in all files in a folder. I want to find all lines that contain these strings and print the result for each file in only one line.

I used grep and awk but the result is always spread over multiple lines. Can anybody help me to find a good method for that?

Please note that there can be multiple matches of some of the search strings within a single file, like two times text3, and i need both of them in output.

  • Please specify more clearly what the result is supposed to look like (perhaps give an example), by editing your question. – Ned64 Jan 15 '20 at 9:32
0

try this:

grep -Er "string 1|string 2|string 3" /folder|\
awk '{COLON1=index($0,":")
      FILE=substr($0,1,COLON1)
      if (FILE!=PREVFILE) { printf "\n"FILE": "} else printf " % "
      printf "%s",substr($0,COLON1+1)
      PREVFILE=FILE
     }
     END {print "\n"}'

This puts all results for each file on one line, each result (if more than one) is separated by ' % '. It will search all files in the specified folder (but not any subfolders). I've put it on multiple lines for ease of comprehension, but it can be done as a one-liner - just use semi-colons between the awk commands instead of newlines.

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.