Last active
February 28, 2017 09:43
-
-
Save mydreambei-ai/53c396e6a92678533943d19708a1c1ca to your computer and use it in GitHub Desktop.
bash convert column file like /etc/passwd to json
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
#!/bin/bash | |
# ./csv2json.sh -s ":" -f /etc/passwd -F 1,7 -N user,shell|json_pp | |
usage() { echo "Usage: $0 [-s <field seprator>] [-f <file>] [-F <fields>] [-N <names>]" 1>&2; exit 1;} | |
while getopts ":s:f:F:N:" o;do | |
case "${o}" in | |
s) | |
SEP=${OPTARG} | |
;; | |
f) | |
FILE=${OPTARG} | |
;; | |
F) | |
FIELDS=${OPTARG} | |
;; | |
N) | |
NAMES=${OPTARG} | |
;; | |
*) | |
usage | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
if [ -z ${SEP} ] || [ -z ${FILE} ] || [ -z ${FIELDS} ] || [ -z ${NAMES} ] ;then | |
usage | |
fi | |
NEWFDS=(${FIELDS//,/ }) | |
NEWNS=(${NAMES//,/ }) | |
if [ ${#NEWFDS[@]} -eq ${#NEWNS[@]} ]; then | |
SIZE=${#NEWNS[@]} | |
lines=() | |
for ((i=0; i<${SIZE}; i++)); | |
do | |
lines+=$(echo -En "gsub(/[ \\t]+/, \"\", \$${NEWFDS[$i]});") | |
done | |
lines+=$(printf "%s" "printf(\"{") | |
for ((i=0; i<${SIZE}; i++)); | |
do | |
if (( i == ${SIZE}-1 ));then | |
lines+=$(echo -En "\\"\"${NEWNS[$i]}\\"\":\\"\"%s\\"\"") | |
else | |
lines+=$(echo -En "\\"\"${NEWNS[$i]}\\"\":\\"\"%s\\"\",") | |
fi | |
done | |
lines+=$(echo -En "}\n\"") | |
for ((i=0;i<${SIZE};i++)) | |
do | |
lines+=$(echo -En ",\$${NEWFDS[$i]}") | |
done | |
lines+=$(echo -En ")") | |
else | |
echo "-F -N 参数应该一致" | |
usage | |
fi | |
LINE=$(printf " %s" ${lines[*]}) | |
cat ${FILE}| awk -F ${SEP} "{$LINE}"|awk 'BEGIN{ORS=","}{print}END{ORS="\n"}'|sed 's/^/[/;s/,$/]/'|more |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://datascienceatthecommandline.com/#tools this is useful too, (scrape is handy)
good luck!