Advertisement
Little_hobbit

bash string finder in files

Oct 7th, 2020 (edited)
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.43 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. arg=
  4. case $# in
  5.     1)
  6.         pattern=$1
  7.         dir=./
  8.         ;;
  9.     2)
  10.         if [ -d $1 ]
  11.         then
  12.             dir=$1
  13.         else
  14.             arg=$1
  15.             dir=./
  16.         fi
  17.         pattern=$2
  18.         ;;
  19.     3)
  20.         arg=$1
  21.         dir=$2
  22.         pattern=$3
  23.         ;;
  24. esac
  25.  
  26. # echo "$arg"
  27. # echo "$pattern"
  28. # echo "$dir"
  29.  
  30. # Check incorrect argument input
  31. if [[ $# -eq 0 || $# -gt 3 || !(-d $dir) || "$arg" != "-r" && -n $arg ]]
  32. then
  33.     echo Usage: strfinder [KEY] [DIR] [PATTERN]
  34.     echo Key: -r for search in the subdirectories
  35.     exit 1
  36. fi
  37.  
  38. rep=true
  39.  
  40. # main loop
  41. while [[ $rep=true && -n $pattern ]]
  42. do
  43.     # output pattern and target dir
  44.     echo
  45.     echo "Search $pattern in $dir"
  46.     echo
  47.  
  48.     # Counter of matches
  49.     count=0
  50.  
  51.     # work with files, witch consider pattern string
  52.     for file in `grep $arg -l -s $pattern $dir*`
  53.     do
  54.         let "count++"
  55.        
  56.         # Out file and commands
  57.         echo
  58.         echo "Found \"$pattern\" in file: $file"
  59.         read -p "[R]emove file, [B]an for other users, [Nothing] to do nothing: " op
  60.         echo
  61.         case $op in
  62.             R | r) rm $file && echo "File $file removed" || echo "Can't remove file $file" ;;
  63.             B | b) chmod og-wrx $file && echo "File $file was banned for other" || echo "Can't ban file $file" ;;
  64.             "") continue ;;
  65.             *) echo "Incorrect operation" ;;
  66.         esac
  67.    
  68.         echo
  69.     done
  70.  
  71.     # if pattern wasn't found
  72.     if [ $count -eq 0 ]
  73.     then
  74.         echo "No files was found."
  75.         read -p "Input new string for search: " pattern
  76.     else
  77.         # else break loop
  78.         break
  79.     fi
  80.  
  81. done
  82.  
  83. echo
  84. echo "Done!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement