添加多个列到同一文件

huangapple go评论53阅读模式
英文:

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\&lt;=final_col_count;i++))
do
testvar=`expr $i + $inp_dummy_col_count`  
cat input_file.csv | cut -d, -f$testvar \&gt;\&gt; output.csv  
cat input_file.csv | cut -d, -f$i \&gt;\&gt; 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&lt;=final_col_count; i++))
do
  testvar=$((i + inp_dummy_col_count))
  cut -d, -f$i,input_file.csv | paste -sd &#39;,&#39; - &gt;&gt; output.csv
  cut -d, -f$testvar,input_file.csv | paste -sd &#39;,&#39; - &gt;&gt; output.csv
done

huangapple
  • 本文由 发表于 2023年5月30日 03:03:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定