`qsv cat *.csv` retroactively add column(s) w/ empty rows
Is your feature request related to a problem? Please describe.
I need to concatenate hundreds of csv files together, and, some of the latest ones have extra column names.
When I run qsv cat *.csv I understandably get an error that the later csv file headers do not match the earlier ones.
Describe the solution you'd like
I'd like a command that compiles all the headers ahead of time (i.e. qsv headers -j --intersect *.csv) and then concatenates the csv files together, supplying empty values for the csv files that did not have the new columns in them.
disclaimer
Its entirely possible that there is a way to do what I am requesting with the available commands, but I am too dumb to figure it out. If thats the case, would anyone be so kind as to give me hint.
I rubber ducked myself... lol... found the option I needed smh
for the record, this was my solution
#!/bin/bash
# bash scripts/fix.sh ./fixed "*.csv"
DIST=$1
TARGETS=$2
mkdir -p $DIST
# Step 1: collect the unique header names by parsing all the csv files
unique_headers_list=$(qsv headers -j --intersect $TARGETS | tr '[:upper:]' '[:lower:]' | sort -u)
unique_headers_comma=$(echo $unique_headers_list | tr ' ' ',')
# Step 2: For each CSV file, add missing headers with default values
FILES=($TARGETS)
for file in "${FILES[@]}"; do
FILENAME=${file##*/}
OUT="$DIST/$FILENAME"
# make headers lowercase
LOWERCASE=$OUT.lowercase
qsv input $file | awk 'NR==1 {print tolower($0)} NR>1 {print}' > $LOWERCASE
mv $LOWERCASE $OUT
# find the missing headers, if any
MISSING_HEADERS=$(echo -e "$(qsv headers -j $OUT)\n$unique_headers_list" | sort | uniq -u | tr '\n' ',' | sed 's/,$//' | sed 's/^,//')
# add missing headers with empty values
FULL=$OUT.full
echo $MISSING_HEADERS | qsv cat columns -o $FULL -p $OUT -
mv $FULL $OUT
# the order of headers cannot be assumed, they must be selected by name
ORDERED=$OUT.ordered
qsv select $unique_headers_comma -o $ORDERED $OUT
mv $ORDERED $OUT
done
Great @isaacadams !
Do you mind adding your recipe to the Cookbook?
I'd love to. I'll submit a PR later today.
@jqnatividad done: https://github.com/jqnatividad/qsv/wiki/Cookbook/ae3bc0e48597f5981c6cf0ecec84d34ce3b0f636
Hi @isaacadams ,
We're currently cataloging how qsv is used in the wild.
Do you mind sharing yours here?
https://github.com/jqnatividad/qsv/discussions/1529
Thanks! We have big plans for qsv in 2024 and knowing how its used would be really helpful.