简体   繁体   English

如何在bash中将通用标头添加到csv文件

[英]How to add a generic header to a csv file in bash

I want a bash script to add a header line (with generic column names) to a CSV file. 我希望bash脚本将标头行(具有通用列名)添加到CSV文件。

My CSV file content: 我的CSV文件内容:

a,b,c,d,e,f,g,h,i,j
a,b,c,d,e,f,g,h,i,j

Desired CSV file content: 所需的CSV文件内容:

1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,j
a,b,c,d,e,f,g,h,i,j

I have been trying to convert between CSV and ARFF file formats, however the CSV2Arff.java code example from Weka requires the input CSV file to have a header, but my CSV file has none. 我一直在尝试在CSV和ARFF文件格式之间进行转换,但是来自WekaCSV2Arff.java代码示例要求输入CSV文件具有标头,但我的CSV文件没有。

Usage: 用法:

./add_header.sh "input.csv"

The bash script (ie add_header.sh ) takes the csv file name as its 1 argument. bash脚本(即add_header.sh )将csv文件名作为其1参数。

timestamp=$(date +"%Y-%m-%d_%H-%M")
input_csv_file=$1
output_csv_file="header_"$timestamp"_"$input_csv_file

o=""
# Find the number of columns (commas) in the first row
n=$(($(head -n1 $input_csv_file | sed 's/[^,]//g' | wc -c)))    

for i in $(seq 1 $n);  # Get a list of numbers equal to column qty
do
        o=$o""$i",";
done

#Write the numbers with commas to first line of new file.
echo $o > $output_csv_file              
#Append whole of other file to new file.
cat $input_csv_file >> $output_csv_file 

Output: is a new file containing the header (with comma-separated numbered columns) followed by the original CSV file content. 输出:是一个新文件,其中包含标头(带有逗号分隔的编号列),后跟原始CSV文件内容。 eg 例如

1,2,3,4,5,6,7,8,9,10,
a,b,c,d,e,f,g,h,i,j
a,b,c,d,e,f,g,h,i,j

this can be done in one line in the shell (bash). 这可以在shell(bash)中一行完成。 For example if using an example file called "dat.csv" 例如,如果使用示例文件“ dat.csv”

$ cat dat.csv
a,b,c,d,e,f,g,h,i,j
a,b,c,d,e,f,g,h,i,j

then 然后

$ cat <(seq -s, 1 $(( `head -n 1 dat.csv | tr -dc "," | wc -c` + 1 ))) dat.csv
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,j
a,b,c,d,e,f,g,h,i,j

you can put the result in a new file like this: 您可以将结果放入这样的新文件中:

$ cat <(seq -s, 1 $(( `head -n 1 dat.csv | tr -dc "," | wc -c` + 1 ))) dat.csv > newfile.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM