[英]Cat one .csv file with all other files in directory
I have multiple csv files that each needs header data placing in row 1, from a seperate csv file which is 1 line in length. 我有多个csv文件,每个文件需要放置在第1行的标题数据,来自一个长度为1行的单独csv文件。 The file is called Anon_student_ID, and every other file in the directory needs this data as line 1 while retaining it's file name. 该文件名为Anon_student_ID,目录中的每个其他文件都需要此数据作为第1行,同时保留其文件名。
I am trying to use the cat function from the command line. 我试图从命令行使用cat函数。
My attempted to solution was - $ cat Anon_student_ID.csv *.csv > *.csv
我试图解决的问题是 - $ cat Anon_student_ID.csv *.csv > *.csv
However, I get bash: *.csv: ambiguous redirect
, 但是,我得到了bash: *.csv: ambiguous redirect
,
Could someone explain why it isn't taking the second filename and using it as the output file name? 有人可以解释为什么它没有采用第二个文件名并将其用作输出文件名吗? And what would be a better way of doing this. 什么是更好的方式来做到这一点。
Thanks 谢谢
#!/bin/bash
shopt -s nullglob
shopt -s extglob
TEMP=$(mktemp)
IFS= read -r HEADER < Anon_student_ID.csv
for CSV in !(Anon_student_ID).csv; do
{ echo "$HEADER"; cat "$CSV"; } > "$TEMP" && cat "$TEMP" > "$CSV"
done
rm -f "$TEMP"
nullglob
prevents patterns from presenting themselves when no match is found. nullglob
可防止模式在未找到匹配项时显示。 extglob
enables extended patterns like !(...)
. extglob
支持扩展模式,如!(...)
。 !(Anon_student_ID).csv
matches all CSV files not having the filename Anon_student_ID
. !(Anon_student_ID).csv
匹配所有没有文件名Anon_student_ID
CSV文件。 sed
is good but it will look hacky on this. sed
很好,但它会看起来很hacky。 It would require repeated reading of the header file as well. 这也需要重复读取头文件。 If files are not that big, using an array for a buffer instead of a temporary file would be good too: 如果文件不是那么大,使用数组作为缓冲区而不是临时文件也是好的:
#!/bin/bash
shopt -s nullglob
shopt -s extglob
[[ BASH_VERSINFO -ge 4 ]] || exit 1 ## Make sure we have `readarray`
IFS= read -r HEADER < Anon_student_ID.csv
for CSV in !(Anon_student_ID).csv; do
readarray -t LINES < "$CSV"
printf '%s\n' "$HEADER" "${LINES[@]}" > "$CSV"
done
As a one-liner: 作为单线:
mv Anon_student_ID.csv Anon_student_ID; for i in *.csv; do cat Anon_student_ID > tmpfile; cat ${i} >> tmpfile; mv tmpfile ${i}; done; mv Anon_student_ID Anon_student_ID.csv
In a readable format: 以可读格式:
#!/bin/bash
mv Anon_student_ID.csv Anon_student_ID
for i in *.csv; do
cat Anon_student_ID > tmpfile
cat ${i} >> tmpfile
mv tmpfile ${i}
done
mv Anon_student_ID Anon_student_ID.csv
Anon_student_ID is renamed, so it will not be used for appending itself to itself, since it would match *.csv
, too. Anon_student_ID被重命名,因此它不会用于将自身附加到自身,因为它也会匹配*.csv
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.