How can I omit the header row in my csv file with sort?
So far I have this:
sort -o ./trans.csv -k 1,1n ./trans.csv
It works well apart from the header row gets sorted also.
To keep the header in your output, and sort all non-header lines:
# create a temporary file to store output to
infile="trans.csv"
tempfile=$(mktemp "${infile}.XXXXXX")
if {
IFS= read -r header # read header from input to variable
printf '%s\n' "$header" # write header from variable to output
sort -k 1,1n # pass all other input to output through sort
} <"$infile" >"$tempfile"; then # if sort reports success (exit status 0)
mv -- "$tempfile" "$infile" # ...then atomically rename over input
else # if sort fails...
echo "ERROR: Output file and input file have different line counts" >&2
rm -f "$tempfile" # then delete the temporary file.
false # and ensure that $? reflects a failure
fi
Note that the if block only checks the exit status of sort, on the theory that we care more about whether the data made it through than the header. Consider using &&s instead of newlines to attach the items in the block if this isn't preferred.
( sed -u 1q; sort -k 1,1n ) < trans.csv > trans-sorted.csv
(so suggested in the GNU Coreutils Manual)
The -u option is important to not lose data (see comments).
or:
( read header; echo $header; sort -k 1,1n ) < trans.csv > trans-sorted.csv
To end up with the same filename: Add && mv trans-sorted.csv trans.csv:
( read header; echo $header; sort -k 1,1n ) < trans.csv > trans-sorted.csv && mv trans-sorted.csv trans.csv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With