开发者

How to add custom line endings in text file (e.g. I want to add a line ending after all periods)

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 period开发者_StackOverflow中文版s 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!


perl -pne 's/\./\.\n/g' < input_file > output_file


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.


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.


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜