为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中跳转到文件中的特定行

在 Go 中跳转到文件中的特定行

Go
温温酱 2021-12-13 18:16:14
在 Go 中是否可以跳转到文件中的特定行号并删除它?类似于python 中的linecache 的东西。我正在尝试匹配文件中的一些子字符串并删除相应的行。我已经处理的匹配部分,我有一个包含行号的数组,我需要删除,但我一直在思考如何删除文件中的匹配行。
查看完整描述

3 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

这是一个老问题,但如果有人正在寻找解决方案,我编写了一个包来处理文件中的任何行。链接在这里。它可以打开一个文件并搜索到任何行位置,而无需将整个文件读入内存并进行拆分。


import "github.com/stoicperlman/fls"


// This is just a wrapper around os.OpenFile. Alternatively 

// you could open from os.File and use fls.LineFile(file) to get f

f, err := fls.OpenFile("test.log", os.O_CREATE|os.O_WRONLY, 0600)

defer f.Close()


// return begining line 1/begining of file

// equivalent to f.Seek(0, io.SeekStart)

pos, err := f.SeekLine(0, io.SeekStart)


// return begining line 2

pos, err := f.SeekLine(1, io.SeekStart)


// return begining of last line

pos, err := f.SeekLine(0, io.SeekEnd) 


// return begining of second to last line

pos, err := f.SeekLine(-1, io.SeekEnd) 

不幸的是,我不确定您将如何删除,这只是让您到达文件中的正确位置。对于您的情况,您可以使用它转到要删除的行并保存位置。然后寻找下一行并保存。您现在有要删除的行的书挡。


// might want lineToDelete - 1

// this acts like 0 based array

pos1, err := f.SeekLine(lineToDelete, io.SeekStart)


// skip ahead 1 line

pos2, err := f.SeekLine(1, io.SeekCurrent)


// pos2 will be the position of the first character in next line

// might want pos2 - 1 depending on how the function works

DeleteBytesFromFileFunction(f, pos1, pos2)


查看完整回答
反对 回复 2021-12-13
?
喵喵时光机

TA贡献1846条经验 获得超7个赞

根据我对 linecache 模块的读取,它需要一个文件并将其分解为基于 '\n' 行结尾的数组。您可以使用strings或bytes复制 Go 中的相同行为。您还可以使用bufio库逐行读取文件,并仅存储或保存所需的行。


package main


import (

    "bytes"

    "fmt"

)

import "io/ioutil"


func main() {


    b, e := ioutil.ReadFile("filename.txt")

    if e != nil {

        panic(e)

    }

    array := bytes.Split(b, []byte("\n"))


    fmt.Printf("%v", array)

}


查看完整回答
反对 回复 2021-12-13
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

我编写了一个小函数,允许您从文件中删除特定行。


package main


import (

    "io/ioutil"

    "os"

    "strings"

)


func main() {

    path := "path/to/file.txt"

    removeLine(path, 2)

}


func removeLine(path string, lineNumber int) {

    file, err := ioutil.ReadFile(path)

    if err != nil {

        panic(err)

    }


    info, _ := os.Stat(path)

    mode := info.Mode()


    array := strings.Split(string(file), "\n")

    array = append(array[:lineNumber], array[lineNumber+1:]...)

    ioutil.WriteFile(path, []byte(strings.Join(array, "\n")), mode)

}


查看完整回答
反对 回复 2021-12-13
  • 3 回答
  • 0 关注
  • 342 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号