Last active
April 25, 2024 11:14
-
-
Save WellingtonEspindula/5f168d317afbde002eb5006946e22efc to your computer and use it in GitHub Desktop.
Comma-based CSV file reader for .bashrc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Bash utility aliases/functions to read huge CSV files | |
# The both functions read the first n lines from a file | |
# Normal version (open the columnized file in less) | |
readcsv() { | |
local lines=$1 \ | |
filename=$2 | |
head -n "$lines" "$filename" | column -tns ',' | less -S | |
} | |
# Improved version | |
# (colorized, allows reverse reading as optional arg, and number of lines as optional arg) | |
readccsv() { | |
local filename | |
local lines | |
local reverse=false | |
local delimiter=',' | |
while [ "$#" -gt 0 ]; do | |
case "$1" in | |
-r|--reverse) | |
reverse=true | |
shift | |
;; | |
-d|--delimiter) | |
if [ -n "$2" ]; then | |
delimiter="$2" | |
shift 2 | |
else | |
echo "Error: Missing argument for delimiter option." | |
return 1 | |
fi | |
;; | |
*) | |
if [ -z "$filename" ]; then | |
filename="$1" | |
elif [ -z "$lines" ]; then | |
lines="$1" | |
else | |
echo "Invalid argument: $1" | |
return 1 | |
fi | |
shift | |
;; | |
esac | |
done | |
if [ -z "$filename" ]; then | |
echo "Usage: readccsv [-r|--reverse] [-d|--delimiter <delimiter>] <filename> [lines]" | |
return 1 | |
fi | |
if [ "$reverse" = true ]; then | |
tail -n "${lines:-$(wc -l < "$filename")}" "$filename" | |
else | |
head -n "${lines:-$(wc -l < "$filename")}" "$filename" | |
fi | awk -F"$delimiter" '{ | |
num_columns = NF; # Get the number of columns from the input | |
for (i = 1; i <= num_columns; i++) { | |
color = 30 + (i%8); # Set color based on column number | |
printf "\033[1;%dm%s\t\033[00m", color, $i; | |
} | |
printf "\n"; | |
}' | column -s$'\t' -t | less -SRN | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment