Poor man's XPath library https://pagure.io/shellfu-bash-pxpath

pxpath.sh.skel 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/bin/bash
  2. shellfu import pretty
  3. #
  4. # Poor man's xpath tool
  5. #
  6. # Most good xpath qruery tools won't work on RHEL5; Perl's XML::XPath
  7. # is even missing aarch64 in RHEL7 (not sure if this is intentional).
  8. #
  9. # For this reason this simple script exists; it should only require
  10. # libxml2 and its Python bindings.
  11. #
  12. pxpath() {
  13. #
  14. # Run XPath query $1 on file $2, register namespaces $3..
  15. #
  16. # Usage:
  17. #
  18. # pxpath [-f FMT] EXPR FILE [NSNAME:NSURI]..
  19. #
  20. # Run EXPR expression on XML FILE using Python bindings to libxml2.
  21. # Optionally, you can specify own namespaces; each has to have name
  22. # and reference URI.
  23. #
  24. # FMT is printf-like format string with single '%s' to which every
  25. # match is inserted prior to printing. Default is '%s\n', that is.
  26. # each match is terminated with single newline.
  27. #
  28. # FILE can be '-' (single dash), in which case standard input
  29. # is (cached and) parsed.
  30. #
  31. # If DEBUG environment variable is set to '1', will print match
  32. # debug info to standard error output.
  33. #
  34. local query
  35. local file
  36. local tmp
  37. local es=0
  38. while true; do case $1 in
  39. -f) fmt+=("$2"); shift 2 || { __pxpath__usage; return 2; } ;;
  40. -*) __pxpath__usage; return 2 ;;
  41. *) break ;;
  42. esac done
  43. query=$1; file=$2; shift 2
  44. test -n "$query" || { __pxpath__usage; return 2; }
  45. case $file in
  46. "")
  47. __pxpath__usage
  48. return 2
  49. ;;
  50. -)
  51. tmp=$(mktemp -t pxpath.stdin.XXXXXXXX)
  52. cat > "$tmp"
  53. file=$tmp
  54. ;;
  55. *)
  56. test -f "$file" || {
  57. warn "no such file, ignoring query: $file"
  58. return 1
  59. }
  60. esac
  61. #shellcheck disable=SC2154
  62. "$_PXPATH__BIN" \
  63. "$query" "$file" "$@"; es=$?
  64. test -n "$tmp" && rm "$tmp"
  65. return $es
  66. }
  67. # # code below should not be called #
  68. # INTERNAL # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  69. # # not even as XPath expression #
  70. #
  71. # Path to pxpath python script
  72. #
  73. _PXPATH__BIN=${_PXPATH__BIN:-__SHELLFU_LIBEXEC__/pxpath}
  74. __pxpath__usage() {
  75. #
  76. # Print usage message for function pxpath__$1
  77. #
  78. local base="usage: pxpath"
  79. mkusage -E "$base [-f FMT] EXPR FILE [NSNAME:NSURI]"
  80. }
  81. #shellfu module-version=__MKIT_PROJ_VERSION__