Golang如何将一行文本转换为单词切片

Golang如何将一行文本转换为单词切片 众所周知,Go语言不支持像 service httpd restart 这样的长Linux命令,我们必须通过 exec.Command("service", "https", "restart").Output() 来运行它。

我正在考虑创建一个名为 shell_exec() 的函数,它接收一个字符串参数,并通过空格将其转换为切片,这样我们就可以通过 exec.Command 来运行命令。 例如 shell_exec("service httpd restart"),然后 shell_exec 函数会将 service httpd restart 转换为三个不同的单词 servicehttpdrestart,接着我们就可以将这些单词传递给 exec.Command().Output()

有人有什么想法吗?


更多关于Golang如何将一行文本转换为单词切片的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

你好, 你可以使用 strings.Split 函数 https://golang.org/pkg/strings/#Split 例如:

// command - shell_exec 的一个参数
args := strings.Split(command, " ")
exec.Command(args...).Output()

更多关于Golang如何将一行文本转换为单词切片的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


为了匹配函数签名,需要将其写为

exec.Command(args[0], args[1:]...)

在 VS Code 中,在 ... 处我遇到了这个错误 - can only use ... with matching parameter compiler 并且在使用 go build 时,我遇到了这个错误:

# command-line-arguments
./gocmd.go:14:27: not enough arguments in call to exec.Command
        have ([]string...)
        want (string, ...string)

可以使用 strings.Fields 函数将一行文本按空格分割成单词切片。这个函数会按空白字符(空格、制表符、换行符等)分割,并忽略连续的空格。

示例代码:

package main

import (
    "fmt"
    "strings"
)

func shell_exec(cmd string) []string {
    return strings.Fields(cmd)
}

func main() {
    cmd := "service httpd restart"
    args := shell_exec(cmd)
    fmt.Printf("%#v\n", args) // 输出: []string{"service", "httpd", "restart"}
}

如果需要处理带引号的参数(例如 echo "hello world"),可以使用 shlex.Split 函数:

package main

import (
    "fmt"
    "github.com/google/shlex"
)

func shell_exec(cmd string) ([]string, error) {
    return shlex.Split(cmd)
}

func main() {
    cmd := `echo "hello world" && ls -l`
    args, err := shell_exec(cmd)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", args) // 输出: []string{"echo", "hello world", "&&", "ls", "-l"}
}

对于简单的空格分割场景,strings.Fields 足够使用。如果需要处理复杂的shell命令语法(引号、转义符等),建议使用 shlex.Split

回到顶部