Reputation: 1399
I am attempting to minimize files using cmd.
The code:
func minify(path string) {
if exists(path) {
fmt.Println("File exist")
} else {
fmt.Println("File NOT exist")
}
cmdStr := `sed ':a;N;$!ba;s/\\n//g' ` + path + " > " + path
fmt.Println(cmdStr)
cmd := exec.Command(cmdStr)
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
func exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
The function exist() verifies that the file exists:
2021/04/20 14:14:53 /media/peter/Elements/Code/free-quotes.info/ubuntu/aws/Go/views/500.min.html
File exist
But when trying to run the command sed ':a;N;$!ba;s/\\n//g' /media/peter/Elements/Code/free-quotes.info/ubuntu/aws/Go/views/500.min.html > /media/peter/Elements/Code/free-quotes.info/ubuntu/aws/Go/views/500.min.html
I get no such file or directory
Based on feedback below I tried
func minify(oldPath string, newPath string) {
cmd := exec.Command("sed", ":a;N;$!ba;s/\n//g", oldPath, ">", newPath)
if err := cmd.Run(); err != nil {
fmt.Println(whereami.WhereAmI(), err)
}
}
But now I get:
File: main.go Function: main.minify Line: 91 exit status 1
Upvotes: 0
Views: 246
Reputation: 227
You are passing all parts including path and arguments in one single argument. However, when you look at Command function, it requires path and arguments seperately as it is stated in the following document. https://golang.org/pkg/os/exec/#Command
So I believe you should edit your code like below; exec.Command("sed", ":a;N;$!ba;s/\n//g", fPath1, ">", fPath2)
Upvotes: 0
Reputation: 1
If you want to remove all newlines, you can just use Go directly:
package main
import (
"bytes"
"os"
)
func main() {
b, e := os.ReadFile("file.txt")
if e != nil {
panic(e)
}
b = bytes.ReplaceAll(b, []byte{'\n'}, nil)
println(string(b))
}
https://golang.org/pkg/bytes#ReplaceAll
Upvotes: 2