添加多个列到同一文件

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

Add multiple columns to same file

问题

我的输入文件是名为input_file.csv的文件,其中包含以下数据:

  1. Fname,Lname,Age,Gender,Address,Age,Gender,Address
  2. ABC,EFG,33,M,India,Age,Gender,Address
  3. PQR,XYZ,30,F,Canada,Age,Gender,Address

我想要动态地将第6列和第3列添加到一个新文件output.csv中。因此,我尝试了以下代码:

  1. final_col_count=8 -- 总列数
  2. inp_dummy_col_count=6 --- 变动列的总数
  3. for ((i=3;i<=final_col_count;i++))
  4. do
  5. testvar=`expr $i + $inp_dummy_col_count`
  6. cat input_file.csv | cut -d, -f$testvar >> output.csv
  7. cat input_file.csv | cut -d, -f$i >> output.csv
  8. done

我得到的输出如下:

  1. Age
  2. Age
  3. Age
  4. Age
  5. 33
  6. 30

而我想要的输出是:

  1. Age,Age
  2. Age,33
  3. Age,30

有谁可以帮助我解决这个问题?

英文:

My input file is input_file.csv with data as below:

  1. Fname,Lname,Age,Gender,Address,Age,Gender,Address
  2. ABC,EFG,33,M,India,Age,Gender,Address
  3. 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:

  1. final_col_count=8 -- total number of columns
  2. inp_dummy_col_count=6 --- total number of varying columns
  3. for ((i=3;i\&lt;=final_col_count;i++))
  4. do
  5. testvar=`expr $i + $inp_dummy_col_count`
  6. cat input_file.csv | cut -d, -f$testvar \&gt;\&gt; output.csv
  7. cat input_file.csv | cut -d, -f$i \&gt;\&gt; output.csv
  8. done

I am getting output as below:

  1. Age
  2. Age
  3. Age
  4. Age
  5. 33
  6. 30

Whereas I want output as below:

  1. Age,Age
  2. Age,33
  3. Age,30

Can anyone help me with this?

答案1

得分: 3

你可以使用 cut 命令:

  1. #!/bin/bash
  2. final_col_count=8 # 总列数
  3. inp_dummy_col_count=6 # 变化列数
  4. for ((i=3; i<=final_col_count; i++))
  5. do
  6. testvar=$((i + inp_dummy_col_count))
  7. cut -d, -f$i,input_file.csv | paste -sd ',' - >> output.csv
  8. cut -d, -f$testvar,input_file.csv | paste -sd ',' - >> output.csv
  9. done
英文:

You can use the cut command:

  1. #!/bin/bash
  2. final_col_count=8 # total number of columns
  3. inp_dummy_col_count=6 # total number of varying columns
  4. for ((i=3; i&lt;=final_col_count; i++))
  5. do
  6. testvar=$((i + inp_dummy_col_count))
  7. cut -d, -f$i,input_file.csv | paste -sd &#39;,&#39; - &gt;&gt; output.csv
  8. cut -d, -f$testvar,input_file.csv | paste -sd &#39;,&#39; - &gt;&gt; output.csv
  9. 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:

确定