从文本文件中删除特定行?
I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.
Any suggestions or examples would be greatly appreciated?
Related Questions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
如果要删除的行是基于该行的内容:
或者如果是基于行号:
If the line you want to delete is based on the content of the line:
Or if it is based on line number:
最好的方法是以文本模式打开文件,使用 ReadLine() 读取每一行,然后使用 WriteLine() 将其写入新文件,跳过要删除的一行。
据我所知,没有通用的从文件中删除一行的功能。
The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.
There is no generic delete-a-line-from-file function, as far as I know.
如果文件不是很大,一种方法是将所有行加载到一个数组中:
One way to do it if the file is not very big is to load all the lines into an array:
希望这个简单而简短的代码将
或使用
Hope this simple and short code will help.
OR use this
实际上,您可以使用 C# 泛型来使其变得非常简单:
You can actually use C# generics for this to make it real easy:
这可以通过三个步骤完成:
This can be done in three steps:
阅读并记住每一行
确定您想要删除的行
的
把剩下的写回上面
文件
Read and remember each line
Identify the one you want to get rid
of
Forget that one
Write the rest back over the top of
the file
我关心文件的原始结束行字符(“\n”或“\r\n”),并希望将它们保留在输出文件中(不要用当前环境的字符覆盖它们,就像其他答案一样)似乎是这样做的)。 因此,我编写了自己的方法来读取一行而不删除行尾字符,然后在我的
DeleteLines
方法中使用它(我想要删除多行的选项,因此使用行号集合来删除)。DeleteLines
被实现为FileInfo
扩展,ReadLineKeepNewLineChars
被实现为StreamReader
扩展(但显然你不必保留就这样)。I cared about the file's original end line characters ("\n" or "\r\n") and wanted to maintain them in the output file (not overwrite them with what ever the current environment's char(s) are like the other answers appear to do). So I wrote my own method to read a line without removing the end line chars then used it in my
DeleteLines
method (I wanted the option to delete multiple lines, hence the use of a collection of line numbers to delete).DeleteLines
was implemented as aFileInfo
extension andReadLineKeepNewLineChars
aStreamReader
extension (but obviously you don't have to keep it that way).您使用的是 Unix 操作系统吗?
您可以使用“sed”流编辑器来完成此操作。 阅读“sed”的手册页
Are you on a Unix operating system?
You can do this with the "sed" stream editor. Read the man page for "sed"
什么?
使用文件打开,查找位置,然后使用空流擦除行。
明白了吗? 简单,流,没有吃内存的数组,速度快。
这在 vb 上工作..示例搜索行culture=id,其中culture是名称值,id是值,我们想将其更改为culture=en,
仅此而已..使用#d
What?
Use file open, seek position then stream erase line using null.
Gotch it? Simple,stream,no array that eat memory,fast.
This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en
that's all..use #d