如何裁剪特定的文本?

huangapple go评论89阅读模式
英文:

How to trim specific text

问题

我有一个文件中的一些文本。文本如下:

#cat tmp 
host = "192.168.2.80"
port = 5432
user = "pnmsuser"
password = "PNMS$$$$$$"
dbname = "pnms"

我想要将文本修整为以下形式:

"192.168.2.80"
5432
"pnmsuser"
"PNMS$$$$$$"
"pnms"

我尝试了以下修整的方法:

func dbFileTrimming() {
    dat, err := ioutil.ReadFile("tmp")
    check(err)

    for key, line := range strings.Split(strings.TrimRight(string(dat), "\n"), "\n") {
        // println(key, line)
        if key == 3 {
            line := string([]rune(line)[11:])
            fmt.Println(line) 
        } else if key == 4 {
            line := string([]rune(line)[9:])
            fmt.Println(line)
        } else {
            line := string([]rune(line)[7:])
            fmt.Println(line)
        }
    }
}

是否有更简单的方法来实现这个目标?

英文:

I have some text in file.Text like below:

#cat tmp 
host = "192.168.2.80"
port = 5432
user = "pnmsuser"
password = "PNMS$$$$$$"
dbname = "pnms"

Just I want text like below after trimming:

"192.168.2.80"
5432
"pnmsuser"
"PNMS$$$$$$"
"pnms"

I try to trim like below

func dbFileTrimming() {
	dat, err := ioutil.ReadFile("tmp")
	check(err)

	for key, line := range strings.Split(strings.TrimRight(string(dat), "\n"), "\n") {
		// println(key, line)
		if key == 3 {
			line := string([]rune(line)[11:])
			fmt.Println(line) 
		} else if key == 4 {
			line := string([]rune(line)[9:])
			fmt.Println(line)
		} else {
			line := string([]rune(line)[7:])
			fmt.Println(line)
		}
	}
}

Is there a simple method for this?

答案1

得分: 1

= 后面的内容截取出来:

for _, line := range strings.Split(strings.TrimRight(string(dat), "\n"), "\n") {
    line = line[strings.Index(line, " = ")+3:]
    fmt.Println(line)
}
英文:

Chop the line after the =:

for _, line := range strings.Split(strings.TrimRight(string(dat), "\n"), "\n") {
     line = line[strings.Index(line, " = ")+3:]
     fmt.Println(line)
}

答案2

得分: 1

这看起来像是一个INI文件,或者类似的文件,可以使用像go-ini这样的库来处理。

另外,你可以尝试使用Strings.split()函数,并将结果放入一个map中。下面是一个简单而未经测试的示例代码:

result := map[string]string{}
for _, line := range strings.Split(string(dat), "\n") {
  split := strings.Split(line, "=")
  key := strings.Trim(split[0], " ")
  value := strings.Trim(split[1], " ")
  result[key] = value
}
英文:

This looks like an INI file, or similar enough so that libraries like go-ini could work.

Alternatively, try Strings.split() and putting the result in a map. Quick and dirty / untested:


result := map[string]string
for _, line := range strings.Split(string(dat), "\n") {
  split := strings.Split(line, "=")
  key := strings.Trim(split[0])
  value := strings.Trim(split[0])
  result[key] = value
}

huangapple
  • 本文由 发表于 2021年6月28日 22:42:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/68165372.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定