views:

90

answers:

5

I have a bunch of text files where I want to add a line ending after each period.

I'm wondering if there is a way to do this by doing replacing all periods with a \n\n, assuming I have the right encoding (unix).

Anyone know how I would do this? Replace .'s with .\n\n and then save as a different file?

Thanks!

A: 

The easy but slow method:
1. Open source file for reading.
2. Open target file for writing.
3. While not EOF of source file:
3.1. read char from source file.
3.2. write char to target file.
3.3. if char == '.' then write "\n\n" to target file.
3.4. End-while
4. Close target file.
5. Close source file.

A faster method is to allocate a bufer, read into the buffer and parse for '.'. Write all chars up to and including the '.'. Write some newlines. Parse some more. Read more, and repeat until EOF.

Thomas Matthews
Why not regexp? This is tedious and unnecessary.
the_drow
This is simple to implement. Doesn't require extra effort to understand regexp nor extra development time to implement a library external to the language. Even Boost sometimes requires extra effort to implement.
Thomas Matthews
+2  A: 
perl -pne 's/\./\.\n/g' < input_file > output_file
Igor Krivokon
The switches `-p` and `-n` are mutually exclusive, but as the man page says, "A -p overrides a -n switch."
msw
+1  A: 

sed s/\\./.\\n\\n/g file > newfile

You might want sed s/\\.\ */.\\n\\n/g file > newfile which will get rid of whitespace trailing periods.

academicRobot
+1  A: 

Igor Krivokon had it right, but it can be improved as

perl -p -i.orig -e 's/\./\.\n/g' input_files ...

which takes any number of input files, edits them in-place and stores the original in input_file.orig as a backup. If you don't want backups, use a bare -i.

msw
+1  A: 

If you are insisting on doing it in C, you could do something like this:

#include <stdio.h>

int main ()
{
  FILE *inFile, *outFile;
  int c;
  inFile=fopen("infile.txt","r");
  outFile=fopen("outfile.txt","w"); 
  if (inFile==NULL || outFile==NULL) perror ("Error opening file");
  else
  {
    while((c = fgetc(inFile)) != EOF){
      if (c == '.'){
        fputc('\n',outFile);
        fputc('\n',outFile);
      }else{
        fputc(c, outFile);
      }   

    } 
    fclose (inFile);
    fclose (outFile);
  }
  return 0;
}
Lucas