Skip to content

Instantly share code, notes, and snippets.

@bpgould
Created December 11, 2024 18:27
Show Gist options
  • Save bpgould/4402947ed4bf20397f1430589b3f2b8f to your computer and use it in GitHub Desktop.
Save bpgould/4402947ed4bf20397f1430589b3f2b8f to your computer and use it in GitHub Desktop.
zsh utility for finding/printing/exploring files across subdirectories of current working directory
# recursive cat/print based on filetype
# requires fzf and bat
catr() {
# Calculate the maximum possible file depth in the current directory
local max_depth
max_depth=$(find . -type d | awk -F/ '{print NF-1}' | sort -nr | head -n1 || echo 0)
# Prompt for file depth if not provided as the first argument
local depth="${1}"
if [[ -z "$depth" ]]; then
echo -n "Enter file depth (max ${max_depth}, default 3): "
read -r depth
depth="${depth:-3}" # Default to 3 if no input
fi
# Validate depth input
if [[ "$depth" -gt "$max_depth" ]]; then
echo "Depth exceeds the maximum possible depth of ${max_depth}."
return 1
fi
# Prompt for file type if not provided as the second argument
local filetype="${2}"
if [[ -z "$filetype" ]]; then
echo -n "Enter file type (e.g., txt, log, * for all files, default *): "
read -r filetype
filetype="${filetype:-*}" # Default to * if no input
fi
# Find files and ensure there are results
local files
files=$(find . -maxdepth "$depth" -type f -name "*.${filetype}" 2>/dev/null)
if [[ -z "$files" ]]; then
echo "No files found matching the criteria."
return 1
fi
# Use fzf to select files
local selected_files
selected_files=$(echo "$files" | \
fzf --prompt="Select a file or use Tab for multi-select: " \
--height=40% \
--border \
--preview "bat $(echo {} | cut -f1)" \
--preview-window=right:60%:wrap \
--multi) # Allow multiple selections
if [[ -z "$selected_files" ]]; then
echo "No files selected."
return 1
fi
# Count selected files and branch logic
local file_count
file_count=$(echo "$selected_files" | wc -l | tr -d ' ')
if [[ "$file_count" -gt 1 ]]; then
# Open multiple files with vi -p (fix Input not from a terminal)
vi -p $(echo "$selected_files")
else
# Display the single selected file with bat
echo "$selected_files" | xargs -r bat
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment