如何在文本文件中添加自定义行结尾(例如,我想在所有句点之后添加行结尾)
我有一堆文本文件,我想在每个句点后添加一行结尾。
我想知道是否有办法通过用 \n\n 替换所有句点来做到这一点,假设我有正确的编码(unix)。
有人知道我会怎么做吗?将 . 替换为 .\n\n 然后另存为其他文件?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
sed s/\\./.\\n\\n/g 文件 > newfile
您可能需要 sed s/\\.\ */.\\n\\n/g file > newfile 这将消除空格尾随句点。
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 说得对,但它可以改进,因为
它可以接受任意数量的输入文件,就地编辑它们并将原始文件存储在
input_file.orig
中作为备份。如果您不想备份,请使用裸-i
。Igor Krivokon had it right, but it can be improved as
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
.如果你坚持用
C
来做,你可以这样做:If you are insisting on doing it in
C
, you could do something like this:简单但缓慢的方法:
1. 开放源文件阅读。
2. 打开目标文件进行写入。
3. 当源文件不是EOF时:
3.1.从源文件中读取字符。
3.2.将字符写入目标文件。
3.3.如果 char == '.'然后将“\n\n”写入目标文件。
3.4.结束时
4. 关闭目标文件。
5. 关闭源文件。
更快的方法是分配一个缓冲区,读入缓冲区并解析“.”。写入“.”之前(包括“.”)的所有字符。写一些换行符。再解析一下。阅读更多内容,然后重复直到 EOF。
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.