【问题标题】:Change specific column value in a data file更改数据文件中的特定列值
【发布时间】:2020-04-10 06:49:15
【问题描述】:

更改数据文件中的特定列值

例如:文件:input_file.out_RD 有以下数据

6710|GB|LONDON|10
6700|GB|LONDON|20
6703|GB|LONDON|15
6876|GB|LONDON|60

现在想将第 4 列的值加倍,所以输出文件应该是 : final_file.out_RD

6710|GB|LONDON|20
6700|GB|LONDON|40
6703|GB|LONDON|30
6876|GB|LONDON|120

【问题讨论】:

  • 恕我直言,您的输出中有错字,看不到双倍的值,请您编辑您的问题一次。
  • 已更正。谢谢@RavinderSingh13

标签: shell csv awk delimiter


【解决方案1】:

你可能想说这样的话:

awk 'BEGIN {FS = OFS = "|"} {$4 *= 2} 1' input_file.out_RD > final_file.out_RD

结果:

6710|GB|LONDON|20
6700|GB|LONDON|40
6703|GB|LONDON|30
6876|GB|LONDON|120

【讨论】:

    【解决方案2】:

    恕我直言 awk 应该比 shell 解决方案更快,请您尝试关注。

    awk 'BEGIN{FS=OFS="|"} {$NF=2 * $NF} 1' Input_file
    

    【讨论】:

      【解决方案3】:

      以下脚本有助于解决问题:

      #!/bin/sh
      
      #input file from which a specific  column to be multiplied
      my_file="/tmp/test/input_file.out_RD"
      
      #multiplication factor value
      multiplication_factor=2.00
      
      while IFS= read -r line
      do
              #read a line from input file and redirect to temporary file tmp_file.txt
              echo "$line" >tmp_file.txt
      
              #extract the forth column value from  temp_file.txt
              original_forth_col_value=`awk -F "|" '{print $4}' tmp_file.txt`
      
              #calculate the final forth column value
              final_forth_col_value=$(echo "$original_forth_col_value * $multiplication_factor" | bc )
              echo $final_forth_col_value
      
              #place the final forth column value in the output file --> final_file.out_RD
              awk -v fv=$final_forth_col_value  -F "|" 'BEGIN {OFS=FS}{$4=fv;print}' tmp_file.txt >> final_file.out_RD
      done < "$my_file"
      

      【讨论】:

      猜你喜欢
      • 2020-07-19
      • 1970-01-01
      • 2019-10-06
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      相关资源
      最近更新 更多