首页 > 解决方案 > Shell: conditional appending or copying of CSVs with header

问题描述

Target:

  1. Copy a CSV with header from one directory to another.
  2. If the CSV already exists in the target directory append it to the existing CSV instead.
  3. Do not append the CSV header.

What is the fastet bash/shell solution with the fewest lines?

Simple solution:

FILE=file.csv
TARGET=path/to/file.csv
if [ -f "$TARGET" ]; then
    sed 1d $FILE >> $TARGET
else 
    cp $FILE $TARGET
fi

标签: bashshellcsv

解决方案


You could do this -

{ [[ -s "$target" ]] && sed 1d "$file" || cat "$file"; } >> "$target"

You'd need to switch the test to -s since the >> $target creates the file before the test happens if it wasn't there...

But don't.

Better to leave it as you have it. Fewer lines isn't better.
In fact, add comments.

Clarity > Brevity.


Lea's awesome version, totally POSIX compliant:

[ -f "$target" ]; tail -n+$(($? ? 1 : 2)) "$file" >>"$target"

That's a thing of beauty, lol >;o]


推荐阅读