cat-recursively.sh 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env bash
  2. set -euo pipefail # bash strict mode
  3. display_help() {
  4. cat <<EOF
  5. Usage: ${0##*/} [OPTIONS] [FILES...]
  6. Process the given files and directories.
  7. Options:
  8. -j Format output for JIRA
  9. -m Format output for Markdown
  10. -4 Format output for 4chan
  11. -h Display this help message and exit
  12. Arguments:
  13. FILES... List of files and directories to process. Directories will be searched for text files, and individual files will be processed as specified.
  14. Examples:
  15. ${0##*/} -j file1.txt file2.txt
  16. ${0##*/} -m dir1 dir2 file3.txt
  17. EOF
  18. exit 2
  19. }
  20. markdown_format(){
  21. local file="$1"
  22. cat <<EOF
  23. ==== ${file} ====
  24. \`\`\`
  25. $(< "$file")
  26. \`\`\`
  27. EOF
  28. }
  29. jira_format(){
  30. local file="$1"
  31. cat <<EOF
  32. ==== ${file} ====
  33. {code:java}
  34. $(< "$file")
  35. {code}
  36. EOF
  37. }
  38. 4chan_format(){
  39. local file="$1"
  40. cat <<EOF
  41. ==== ${file} ====
  42. [code]
  43. $(< "$file")
  44. [/code]
  45. EOF
  46. }
  47. format(){
  48. local file="$1"
  49. case "${format_option:-}" in
  50. j) jira_format "$file" ;;
  51. 4) 4chan_format "$file" ;;
  52. m|*) markdown_format "$file" ;;
  53. esac
  54. }
  55. while getopts 'jm4h' opt; do
  56. case "$opt" in
  57. j|m|4) format_option="$opt" ;;
  58. h|\?|:|*) display_help ;;
  59. esac
  60. done
  61. shift $((OPTIND-1))
  62. for thing in "$@"; do
  63. if [[ -d $thing ]]; then
  64. dirs+=("$thing")
  65. elif [[ -f $thing ]]; then
  66. files+=("$thing")
  67. else
  68. echo "I don't know what is ${thing}"
  69. fi
  70. done
  71. [[ ${dirs:-} ]] && mapfile -t ALL_FILES < <(find "${dirs[@]}" -type f -not \( -path '*/.git/*' -o -path '*/www/*' \) | sort)
  72. [[ ${files:-} ]] && ALL_FILES+=("${files[@]}")
  73. for file in "${ALL_FILES[@]}"; do
  74. if [[ $(file -b --mime-type "$file") =~ 'text' ]]; then
  75. format "$file"
  76. fi
  77. done