bzgrep 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/bin/sh
  2. # Bzgrep wrapped for bzip2,
  3. # adapted from zgrep by Philippe Troin <phil@fifi.org> for Debian GNU/Linux.
  4. ## zgrep notice:
  5. ## zgrep -- a wrapper around a grep program that decompresses files as needed
  6. ## Adapted from a version sent by Charles Levert <charles@comm.polymtl.ca>
  7. PATH="/usr/bin:$PATH"; export PATH
  8. prog=`echo $0 | sed 's|.*/||'`
  9. case "$prog" in
  10. *egrep) grep=${EGREP-egrep} ;;
  11. *fgrep) grep=${FGREP-fgrep} ;;
  12. *) grep=${GREP-grep} ;;
  13. esac
  14. pat=""
  15. while test $# -ne 0; do
  16. case "$1" in
  17. -e | -f) opt="$opt $1"; shift; pat="$1"
  18. if test "$grep" = grep; then # grep is buggy with -e on SVR4
  19. grep=egrep
  20. fi;;
  21. -A | -B) opt="$opt $1 $2"; shift;;
  22. -*) opt="$opt $1";;
  23. *) if test -z "$pat"; then
  24. pat="$1"
  25. else
  26. break;
  27. fi;;
  28. esac
  29. shift
  30. done
  31. if test -z "$pat"; then
  32. echo "grep through bzip2 files"
  33. echo "usage: $prog [grep_options] pattern [files]"
  34. exit 1
  35. fi
  36. list=0
  37. silent=0
  38. op=`echo "$opt" | sed -e 's/ //g' -e 's/-//g'`
  39. case "$op" in
  40. *l*) list=1
  41. esac
  42. case "$op" in
  43. *h*) silent=1
  44. esac
  45. if test $# -eq 0; then
  46. bzip2 -cdfq | $grep $opt "$pat"
  47. exit $?
  48. fi
  49. res=0
  50. for i do
  51. if test -f "$i"; then :; else if test -f "$i.bz2"; then i="$i.bz2"; fi; fi
  52. if test $list -eq 1; then
  53. bzip2 -cdfq "$i" | $grep $opt "$pat" 2>&1 > /dev/null && echo $i
  54. r=$?
  55. elif test $# -eq 1 -o $silent -eq 1; then
  56. bzip2 -cdfq "$i" | $grep $opt "$pat"
  57. r=$?
  58. else
  59. j=$(echo "$i" | sed 's/\\/&&/g;s/|/\\&/g;s/&/\\&/g')
  60. j=`printf "%s" "$j" | tr '\n' ' '`
  61. # A trick adapted from
  62. # https://groups.google.com/forum/#!original/comp.unix.shell/x1345iu10eg/Nn1n-1r1uU0J
  63. # that has the same effect as the following bash code:
  64. # bzip2 -cdfq "$i" | $grep $opt "$pat" | sed "s|^|${j}:|"
  65. # r=${PIPESTATUS[1]}
  66. exec 3>&1
  67. eval `
  68. exec 4>&1 >&3 3>&-
  69. {
  70. bzip2 -cdfq "$i" 4>&-
  71. } | {
  72. $grep $opt "$pat" 4>&-; echo "r=$?;" >&4
  73. } | sed "s|^|${j}:|"
  74. `
  75. fi
  76. test "$r" -ne 0 && res="$r"
  77. done
  78. exit $res