Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

命令行参数比如" "," " 如何在程序运行时不被转义?

  • 编程语言为 golang , 例如实现一个 cut 命令的这个功能: cut -d "" 指定分隔符为制表符, 而当程序运行时, 指定的""在程序中已经变成了"\t",不是自己想要的制表符, 应该如何解决?

package main

import (
    "flag"
    "fmt"
    "strings"
)

// D use -d to specify a separator
var D = flag.String("d", "", "use -d to specify a separator")

func main() {
    flag.Parse()
    originStr := "abcd e f g"
    var resultStr []string
    if *D != "" {
        resultStr = strings.Split(originStr, *D)
    }
    fmt.Println(*D)
    for i := 0; i < len(resultStr); i++ {
        fmt.Println(resultStr[i])
    }
}

编译: go build -o cut

?  test ./cut -d " "   以空格为分隔符

a       b       c       d
e
f
g
?  test ./cut -d ""  以"" 为分隔符,  被转义成普通字符串了

a       b       c       d e f g

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

这说明,命令行不会将字面量t转为制表符。
那么你需要在你的程序里将转义字符转为真实字符。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...