给出file.csv
:
0.99,Apple,Fruit
22.33,Banjo,Instrument
1.95,Chocolate,Snack
和.bashrc
/ .bash_profile
(非GNU):
CEND='\e[0;0m'
CRED='\e[0;31m'
CGREEN='\e[0;32m'
我可以将第一列染成红色,就像这样:
for a in $(cut -f 1 -d, - < file.csv); do printf ${CRED}$a${CEND}'\n'; done
但是如何为其他列着色,然后将结果通过管道传输到column -s, -t
或其他实用程序以显示整个CSV文件?
所需结果:
0.99 Apple Fruit
22.33Banjo Instrument
1.95 ChocolateSnack
|____|________|_________|
RED GREEN BLACK
我正在尝试使用颜色分隔列;不是按制表符或空格。
答案 0 :(得分:2)
您需要使用IFS。
CEND='\e[0;0m'
CRED='\e[0;31m'
CGREEN='\e[0;32m'
while IFS=, read -r col1 col2 col3
do
printf "${CRED}$col1${CGREEN}$col2${CEND}$col3\n"
done < path_to_csv_file
CEND='\e[0;0m'
CRED='\e[0;31m'
CGREEN='\e[0;32m'
CSV_FILE='csv'
read max1 max2 <<< $(awk -F, ' { for (i=1;i<=NF;i++)LENGTH[i]=((x=length($i))>LENGTH[i]?x:LENGTH[i])} END { print LENGTH[1] " " LENGTH[2] }' $CSV_FILE)
while IFS=, read -r col1 col2 col3
do
printf "${CRED}%-*s${CGREEN}%-*s${CEND}%s\n" ${max1} "${col1}" ${max2} "${col2}" "${col3}"
done < $CSV_FILE
答案 1 :(得分:1)
您会考虑使用python
吗?如果是,那么
$ cat file.csv
some,name,thing
0.99,Apple,Fruit
22.33,Banjo,Instrument
1.95,Chocolate,Snack
还有colorize_csv.py
文件
# colorize_csv.py
# Usage: `python colorize_csv.py file.csv`
from csv import DictReader
import sys
green = "\033[32m"
red = "\033[31m"
yellow = "\033[33m"
reset = "\033[00m"
with open(sys.argv[1]) as file:
reader = DictReader(file)
for row in reader:
line = "{}{:<10s} {}{:<10s} {}{:<10s}{}".format(red, row['some'], green, row['name'], yellow, row['thing'], reset)
print(line)