any.sh 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. any() {
  2. # read stdin, grep for any of the words on the command line
  3. #
  4. # Usage: any [grep_flags] "word1" "word2" ...
  5. #
  6. # Example usage:
  7. # cat some_file.txt | any -i "word1" "word2"
  8. #
  9. #
  10. # Insipred by Marcus Ranum's "Artificial Ignornace":
  11. # https://www.ranum.com/security/computer_security/papers/ai/
  12. #
  13. # source this file to define the alias.
  14. local words=()
  15. local grep_flags=()
  16. # Separate grep flags from words
  17. while [ $# -gt 0 ]; do
  18. case "$1" in
  19. -*)
  20. # Argument is a flag (starts with -)
  21. grep_flags+=("$1")
  22. shift
  23. ;;
  24. *)
  25. # Argument is a word
  26. words+=("$1")
  27. shift
  28. ;;
  29. esac
  30. done
  31. # Construct a grep pattern that matches any of the given words
  32. local grep_pattern=""
  33. for word in "${words[@]}"; do
  34. if [ -n "$grep_pattern" ]; then
  35. grep_pattern="${grep_pattern}|${word}"
  36. else
  37. grep_pattern="${word}"
  38. fi
  39. done
  40. # Use grep with specified flags to filter include lines that contain
  41. # any of the specified words
  42. grep "${grep_flags[@]}" -E "($grep_pattern)"
  43. }