我对 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 上运行
最佳答案
此处的区别在于 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/