2

I have been testing using ack, sed, grep trying to search through files in a directory to find a particular string. I am looking through my database files to check to see if passwords are listed in clear text. So far, I have been able to use this command: grep -Ri "search_string" /path_to_Folder

However, this only outputs the files that contain the string. I want to go one step further and print out the line around the string so I don't have to go in and search each file.

I hope that make sense. Thank you so much.

2

If I'm understanding you correctly, to:

print out the line around the string

you can use grep's -C (context) option, like so:

grep -aRi -C 1 "search_string" /path_to_Folder

which will print three lines for every match: the line before the match, the matching line, and the line after the match.

Since the database files were binary, we also need grep's -a flag, so that it treats files as text.

Sample run:

$ grep -aRi jeff *
a/b/c/i:jeff
a/b/i:jeff
a/i:jeff
i:jeff

vs

$ grep -aRi -C1 jeff *
a/b/c/i-hi
a/b/c/i:jeff
a/b/c/i-bye
--
a/b/i-hi
a/b/i:jeff
a/b/i-bye
--
a/i-hi
a/i:jeff
a/i-bye
--
i-hi
i:jeff
i-bye
  • Adding some --color is usually helpful, if your grep and terminal supports that. – a CVn Feb 26 '17 at 15:22
  • Thank you so much, Jeff. I tried that code and it once again tells me the files that match, but don't give me any print out of the matching line. Here is an output. I made 3 text files with the word "test" in it and placed them in a desktop folder. administrator$ grep -Ri -C1 "test" /Users/administrator/Desktop/test\ Folder Here is the output..... Binary file /Users/administrator/Desktop/test Folder/test copy 2.txt matches Binary file /Users/administrator/Desktop/test Folder/test copy.txt matches Binary file /Users/administrator/Desktop/test Folder/test.txt matches – user3324136 Feb 27 '17 at 0:47
  • Ahh, I was afraid of that, but assumed that you were getting results previously, perhaps with flat-file "databases". – Jeff Schaller Feb 27 '17 at 0:52
  • Does it help if you add the -a (or --text) flag to grep? – Jeff Schaller Feb 27 '17 at 0:55
  • The -a definitely made a difference! Thank you. It started outputting some helpful data from the database. I think I can start to modify from there to pull accurate data. Learn something new everyday. Thank you! – user3324136 Feb 27 '17 at 2:04

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.