Grep – recognize carriage return as new line

grepunix-shell

I want to search a webserver running unix for php-files containing a specific string. Usually I use these commands to accomplish this:

find . -name "*.php" -print0 | xargs -0 grep -H -i "the string to search for"

This will find any php file containing "the string to search for", and print the file name and the line in which the match was made.

This has worked great so far, but now I've encountered a server where all the php-scripts don't have any line feeds, but instead only carriage returns. grep doesn't seem to recognize carriage return as new line, so the command above will print the entire contents of a file if there is a match within it, instead of just printing the line.

Any help would be greatly appreciated!

Best Answer

What about using (grep on my Ubuntu, pretty sure most of the grep's out there has this flag)

  -o, --only-matching
         Print only the matched (non-empty) parts of a matching line, with each such >part on a separate output line.

together with

  -b, --byte-offset
         Print  the  0-based byte offset within the input file before each line of >output.  If -o (--only-matching) is specified, print the offset of
         the matching part itself.

Then you have the filename and the part of it you want.

Also, how did you manage to mangle your files like that? I tried using VI to replace newlines with CR only. But that made grep and cat behave very strangely instead.

contents of file test

gggggggggggggggggggg^Mggggggggasdfgggggggg^Mgggggggggggggggggggg

~/test$ grep asdf test

gggggggggggggggggggg

~/test$ cat test

gggggggggggggggggggg

Looks normal in notepad

Related Topic