Why are there different results when using regular expressions when executing commands in the cmd terminal and when executing cmd commands in golang?

Viewed 42

Two different results of executing the command in the cmd terminal and executing the cmd command in golang

cmd

C:\Users\Administrator>cmd /c tasklist | findstr /R /I "\<cmd.exe\>"
cmd.exe                       4852 Console                    1      5,676 K
cmd.exe                      11736 Console                    1      4,836 K

golang

func main() {
    cmd := exec.Command("cmd.exe", "/C", "tasklist", "|", "findstr", "/R", "/I", "cmd.exe")
    output, err := cmd.Output()
    if err != nil {
        panic(err)
    }
    fmt.Println(string(output))

    // Use regular filtering
    cmd2 := exec.Command("cmd.exe", "/C", "tasklist", "|", "findstr", "/R", "/I", "\\<cmd.exe\\>")
    output, err = cmd2.Output()
    if err != nil {
        panic(err)
    }
    fmt.Println(string(output))
}

result:
C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_demo_go.exe
cmd.exe                       4852 Console                    1      5,380 K
cmd.exe                      11816 Console                    1      5,044 K

panic: exit status 1
1 Answers

Thank you for your kind reply. Finally, I solved it in this way:

cmd := exec.Command("cmd.exe", "/C", "tasklist", "|", "findstr", "/R", "/I", "cmd.exe")
output, _ := cmd.Output()
fmt.Println(string(output))
//***************************************************************************//
cmd1 := exec.Command("cmd.exe", "/C", "tasklist")
cmd2 := exec.Command("findstr", "/R", "/I", "\\<cmd.exe\\>")
cmd2.Stdin, _ = cmd1.StdoutPipe()
cmd1.Start()
data, _ := cmd2.Output()
cmd1.Wait()
fmt.Println(string(data))

result:

Result of regular expression not used
cmd.exe                       5188 Console                    1      6,184 K
cmdcmd.exe                    1260 Console                    1      4,980 K

Results of using regular expressions
cmd.exe                       5188 Console                    1      6,184 K

Although the second way is a little more troublesome, it is really useful. I wonder if there is a better way?

Related