Advertisement
Kevin_Zhang

Untitled

May 29th, 2022
1,081
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.56 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. NAME_REGEX=".*"
  4. LINE_L=1
  5. LINE_R=-1
  6. DIR="."
  7. DLIM=""
  8. HAS_WORD="false"
  9. WORDLIST=""
  10.  
  11. ER () {
  12.     echo $1
  13.     exit 1
  14. }
  15.  
  16. while [[ $# > 0 ]]; do
  17.     arg=$1
  18.     shift
  19.     case $arg in
  20.         -name)
  21.             NAME_REGEX=$1
  22.             shift
  23.         ;;
  24.         -l)
  25.             SEG=$1
  26.             if [[ $SEG =~ .*:.* ]]; then
  27.                 ## two parameters
  28.                 LINE_L=${SEG%:*}
  29.                 LINE_R=${SEG##*:}
  30.             else
  31.                 LINE_L=$SEG
  32.                 LINE_R=$SEG
  33.             fi
  34.             if (($LINE_L == 0)); then
  35.                 ER "LINE cannot be 0 sorry QQ"
  36.             fi
  37.             shift
  38.         ;;
  39.         -sep)
  40.             DLIM=$1
  41.             shift
  42.         ;;
  43.         -c)
  44.             WORDLIST=$1
  45.             HAS_WORD="true"
  46.             shift
  47.         ;;
  48.         *)
  49.             DIR=$arg
  50.         ;;
  51.     esac
  52. done
  53.  
  54. WORDLIST=$(tr "," " " <<< $WORDLIST)
  55.  
  56. for i in $(find $DIR -type f); do
  57.     if ! [[ $(basename $i) =~ $NAME_REGEX ]]; then
  58.         continue
  59.     fi
  60.     echo "Processing file $(basename $i):"
  61.  
  62.     ALL=$(wc -l < $i)
  63.     L=$LINE_L
  64.     R=$LINE_R
  65.  
  66.     if (( $L < 0 )); then
  67.         L=$((ALL+L+1))
  68.         if (( $L < 0 )); then
  69.             L=1
  70.         fi
  71.     fi
  72.  
  73.     if (( $R < 0 )); then
  74.         R=$((ALL+R+1))
  75.     fi
  76.  
  77.     if (( $L > $R )); then
  78.         continue
  79.     fi
  80.  
  81.     if [[ $HAS_WORD == "true" ]]; then
  82.  
  83.         if [[ $DLIM == "" ]]; then
  84.             CONT=$(sed -n "${L},${R}p" < $i)
  85.             for w in $WORDLIST; do
  86.                 echo " Word $w occurs: $(grep -o "$w" <<< "$CONT" | wc -l) times"
  87.             done
  88.         else
  89.             for w in $WORDLIST; do
  90.                 T=0
  91.                 CONT=$(sed -n "${L},${R}p" < $i)
  92.                 while IFS="$DLIM" read -ra ADDR; do
  93.                     for b in "${ADDR[@]}"; do
  94.                         if [[ $b == $w ]]; then
  95.                             ((++T))
  96.                         fi
  97.                     done
  98.                 done <<< "$CONT"
  99.                 echo " Word $w occurs: $T times"
  100.             done
  101.         fi
  102.     else
  103.         sed -n "${L},${R}p" < $i
  104.     fi
  105. done
  106.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement