main.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strings"
  7. )
  8. // map for old history records
  9. var history = make(map[string]int)
  10. // file 'h': ${HOME}/.bash_history
  11. // file 't': /tmp/.bash_history******/.bash_history
  12. var h, t file
  13. // Set constant file name
  14. // Why constant? Because it will never be changed due to program purpose.
  15. const fileName string = ".bash_history"
  16. func init() {
  17. h.init(fileName, locHome)
  18. h.Open()
  19. t.init(fileName, locTemp)
  20. t.Open()
  21. }
  22. func main() {
  23. //read old history
  24. scanner := bufio.NewScanner(h.handle)
  25. var i = 0
  26. for scanner.Scan() {
  27. line := strings.TrimSpace(scanner.Text())
  28. history[line] = i
  29. i++
  30. }
  31. delete(history, "")
  32. h.handle.Close()
  33. // push history to temp slice
  34. // and sort by last entry position number
  35. var ah = make([]string, i)
  36. for key, val := range history {
  37. ah[val] = key
  38. }
  39. // write not empty lines to temp file
  40. i = 0
  41. for _, key := range ah {
  42. if len(key) > 0 {
  43. t.handle.WriteString(key + "\n")
  44. i++
  45. }
  46. }
  47. t.handle.Close()
  48. //copy from temp file to home
  49. _, err := CopyFile(t.path, h.path)
  50. if err != nil {
  51. fmt.Println(err)
  52. }
  53. //finnaly remove temp folder
  54. err = os.RemoveAll(t.dir)
  55. if err != nil {
  56. fmt.Print(err)
  57. }
  58. fmt.Printf("wrote %d lines to %s\n", i, h.path)
  59. }