kapott

csvfind.sh

May 31st, 2019
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.76 KB | None | 0 0
  1. #!/usr/bin/env bash
  2.  
  3. # Assumes the CSV file has a proper header!
  4. thisfile="$0"
  5.  
  6. main() {
  7.   local csv_header grep_result
  8.  
  9.   check_args "$@"
  10.  
  11.   grep_result=$(grep -E "${1}" "${2}")
  12.   IFS=',' read -r -a grepArray <<< "$grep_result"
  13.  
  14.   csv_header=$(head -n 1 "${2}")
  15.   IFS=',' read -r -a headerArray <<< "$csv_header"
  16.  
  17.   for index in "${!headerArray[@]}"; do
  18.     printf "%2s%50s%50s\\n" "$index" "${headerArray[index]}" "${grepArray[index]}"
  19.   done
  20. }
  21.  
  22. exit_help() {
  23.     printf "%s\n" "Usage: $thisfile <search regex> <filename>"
  24.     exit 1
  25. }
  26.  
  27. check_args() {
  28.   # Check if we have 2 args
  29.   if [ "$#" -ne 2 ]; then
  30.        exit_help
  31.   fi
  32.  
  33.     # Check that argument 2 is an existing file..
  34.   [[ ! -z $2 ]] && [[ -f "$2" ]] || exit_help
  35. }
  36.  
  37. main "$@"
Advertisement
Add Comment
Please, Sign In to add comment