intellij-idea - Golang 使用 filepath.Glob 的奇怪行为

标签 intellij-idea go glob

我对 Golang 上的 glob 使用感到困惑,我可能缺少一些环境变量。我不知道我这样做是否正确。

这段代码在我的 IDE (Intellij IDEA) 上运行时工作得很好,但是当它通过 go run 在操作系统上运行时它不起作用。我不明白有什么区别。

package main

import (
    "path/filepath"
    "fmt"
    "os"
)

func main() {

    file := os.Args[1]

    matches, err := filepath.Glob(file)

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(fmt.Sprintf("Number of matches:%d", len(matches)))
    fmt.Println(matches)
}

在操作系统上运行

go run globtest.go /Users/bernardovale/glotest/*.bkp
Number of matches:1
[/Users/bernardovale/glotest/test1.bkp]

ls -l /Users/bernardovale/glotest/*.bkp
-rw-r--r--  1 bernardovale  staff  0 May 27 12:06 /Users/bernardovale/glotest/test1.bkp
-rw-r--r--  1 bernardovale  staff  0 May 27 12:06 /Users/bernardovale/glotest/test2.bkp
-rw-r--r--  1 bernardovale  staff  0 May 27 12:06 /Users/bernardovale/glotest/test3.bkp

在 IntelliJ IDEA 上运行

go run on the IDEA

最佳答案

此处的区别在于 shell 正在执行 glob 并向您的应用程序提供各个值。从 shell 执行时,您应该将 glob 括在双引号中,以确保 shell 不会首先对其进行计算。请参阅下面的示例。

Seans-MBP-2:~ sthorne$ echo Testing*
Testing Testing2 Testing3
Seans-MBP-2:~ sthorne$ echo "Testing*"
Testing*

关于intellij-idea - Golang 使用 filepath.Glob 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37487189/

相关文章:

java - Maven 未安装 aws-encryption-sdk-java 依赖项

go - go语言读取并合并两个yaml文件

regex - 如何使用正则表达式 (glob) 搜索文件树

json - 为什么我从 mongodb 的 json 中的某些字段的值全为零?

git - 忽略 git 中的目录链?

java - Java 路径中的星号

java - IntelliJ 14 不断将编码切换为 UTF-8

git - IntelliJ 注释与 git blame

intellij-idea - IntelliJ 在类路径或 bootclasspath 中给出 fatal error : Unable to find package java. lang

sql-server - 使用GORM从GOlang中的SQL处理多个结果集