英文:
Add multiple columns to same file
问题
我的输入文件是名为input_file.csv的文件,其中包含以下数据:
Fname,Lname,Age,Gender,Address,Age,Gender,Address
ABC,EFG,33,M,India,Age,Gender,Address
PQR,XYZ,30,F,Canada,Age,Gender,Address
我想要动态地将第6列和第3列添加到一个新文件output.csv中。因此,我尝试了以下代码:
final_col_count=8 -- 总列数
inp_dummy_col_count=6 --- 变动列的总数
for ((i=3;i<=final_col_count;i++))
do
testvar=`expr $i + $inp_dummy_col_count`
cat input_file.csv | cut -d, -f$testvar >> output.csv
cat input_file.csv | cut -d, -f$i >> output.csv
done
我得到的输出如下:
Age
Age
Age
Age
33
30
而我想要的输出是:
Age,Age
Age,33
Age,30
有谁可以帮助我解决这个问题?
英文:
My input file is input_file.csv with data as below:
Fname,Lname,Age,Gender,Address,Age,Gender,Address
ABC,EFG,33,M,India,Age,Gender,Address
PQR,XYZ,30,F,Canada,Age,Gender,Address
I want to add column 6 and column 3 dynamically to a new file output.csv. So I am trying below code:
final_col_count=8 -- total number of columns
inp_dummy_col_count=6 --- total number of varying columns
for ((i=3;i\<=final_col_count;i++))
do
testvar=`expr $i + $inp_dummy_col_count`
cat input_file.csv | cut -d, -f$testvar \>\> output.csv
cat input_file.csv | cut -d, -f$i \>\> output.csv
done
I am getting output as below:
Age
Age
Age
Age
33
30
Whereas I want output as below:
Age,Age
Age,33
Age,30
Can anyone help me with this?
答案1
得分: 3
你可以使用 cut
命令:
#!/bin/bash
final_col_count=8 # 总列数
inp_dummy_col_count=6 # 变化列数
for ((i=3; i<=final_col_count; i++))
do
testvar=$((i + inp_dummy_col_count))
cut -d, -f$i,input_file.csv | paste -sd ',' - >> output.csv
cut -d, -f$testvar,input_file.csv | paste -sd ',' - >> output.csv
done
英文:
You can use the cut
command:
#!/bin/bash
final_col_count=8 # total number of columns
inp_dummy_col_count=6 # total number of varying columns
for ((i=3; i<=final_col_count; i++))
do
testvar=$((i + inp_dummy_col_count))
cut -d, -f$i,input_file.csv | paste -sd ',' - >> output.csv
cut -d, -f$testvar,input_file.csv | paste -sd ',' - >> output.csv
done
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论