如果等于特定值,请替换列 [英] Replace Column if equal to a specific value

查看:110
本文介绍了如果等于特定值,请替换列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它等于N/A,我想替换CSV中的第四列.我正在尝试将其更改为-1.
我似乎无法使其正常工作.

I'm looking to replace the fourth column in a CSV if it equals N/A. I'm trying to change it to -1.
I can't seem to get this to work.

awk -F , '{ if($4 == "N/A") {$4 = -1} }' test.csv

推荐答案

您可以使用以下awk:

awk -F, '{ $4 = ($4 == "N/A" ? -1 : $4) } 1' OFS=, test.csv

  • 我们将输入和输出字段分隔符设置为,,以将分隔符保留在csv文件中
  • 我们检查第四个字段是否等于"N/A",然后为它分配值-1;如果不等于,则保持原样.
  • 最后的
  • 1会根据您的测试是否成功来打印带或不带修饰的第4列的行.
  • ($4=="N/A"?-1:$4)是用于检查条件$4=="N/A"是否为true的三元运算符.如果?为true,则分配为-1;如果为:为false,则将该字段保持不变.
    • We set the input and output field separators to , to preserve the delimiters in your csv file
    • We check the forth field if it is equal to "N/A" then we assign it the value -1 if not we retain the value as is.
    • 1 at the end prints your line with or without modified 4th column depending if our test was successful or not.
    • ($4=="N/A"?-1:$4) is a ternary operator that checks if the condition $4=="N/A" is true or not. If true ? then we assign -1 and if false : we keep the field as is.
    • $ cat file
      a,b,c,d,e,f
      1,2,3,4,5,6
      44,2,1,N/A,4,5
      24,sdf,sdf,4,2,254,5
      a,f,f,N/A,f,4
      

      $ awk -F, '{ $4 = ($4 == "N/A" ? -1 : $4) } 1' OFS=, file
      a,b,c,d,e,f
      1,2,3,4,5,6
      44,2,1,-1,4,5
      24,sdf,sdf,4,2,254,5
      a,f,f,-1,f,4
      

      这篇关于如果等于特定值,请替换列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆