从文本文件中删除 a 中的每第二行和第三行

发布于 2024-11-16 14:34:45 字数 79 浏览 1 评论 0原文

我目前正在寻找一种删除 txt 文件中的第 (n) 行和第 (n) 行的方法。 例如每第二行和第五行。 有没有办法用脚本或 C# 来做到这一点?

I am currently looking for a way of deleting every (n)th and (n)th line in a txt file.
For example every 2nd and 5th line.
Is there a way of doing this with a script or with C#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧竹 2024-11-23 14:34:45

这段代码是在 VB.NET 中,但我相信这会做你想要的?

    Dim sr As streamreader = Nothing
    Dim sw As StreamWriter = Nothing
    Dim LineString As String = ""
    Dim LineNum As Integer = 0
    Try
        sr = New StreamReader("C:\scratch\input.txt")
        sw = New StreamWriter("c:\scratch\output.txt")
        Do Until sr.EndOfStream
            LineString = sr.ReadLine
            LineNum += 1

            If LineNum Mod 2 = 0 Then
                'don't output 2nd line
            ElseIf LineNum Mod 5 = 0 Then
                'don't output 5th line
            Else
                'write it 
                sw.WriteLine(LineString)
            End If
        Loop
    Catch ex As Exception
        MsgBox("Error - " & ex.Message)
    Finally
        If Not IsNothing(sr) Then sr.Close()
        If Not IsNothing(sw) Then sw.Close()
    End Try

This code is in VB.NET but I believe this will do what you want?

    Dim sr As streamreader = Nothing
    Dim sw As StreamWriter = Nothing
    Dim LineString As String = ""
    Dim LineNum As Integer = 0
    Try
        sr = New StreamReader("C:\scratch\input.txt")
        sw = New StreamWriter("c:\scratch\output.txt")
        Do Until sr.EndOfStream
            LineString = sr.ReadLine
            LineNum += 1

            If LineNum Mod 2 = 0 Then
                'don't output 2nd line
            ElseIf LineNum Mod 5 = 0 Then
                'don't output 5th line
            Else
                'write it 
                sw.WriteLine(LineString)
            End If
        Loop
    Catch ex As Exception
        MsgBox("Error - " & ex.Message)
    Finally
        If Not IsNothing(sr) Then sr.Close()
        If Not IsNothing(sw) Then sw.Close()
    End Try
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文