bash - Shell: conditional appending or copying of CSVs with header
问题描述
Target:
- Copy a CSV with header from one directory to another.
- If the CSV already exists in the target directory append it to the existing CSV instead.
- 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
解决方案
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]
推荐阅读
- android - 自定义键盘的滑动输入
- javascript - 学习 JS - 无法将计数器的结果用于字段
- java - ConcurrentHashMap 上的同步块:锁定将放在什么位置?
- angular - 将类添加到动态创建的组件角度
- android - 图像未显示在 Xamarin Forms Android 项目中
- sql - SQL 循环数月
- java - 是否可以在 mongo db 中使用 Java 将输入作为流插入记录?
- android - Volley 无法访问应用程序中的 URL,Android 10
- css - 滚动不显示整个项目列表
- reactjs - 从项目中删除导入/无周期警告