如果在 Linux 中找到特定行,如何替换 .csv 文件的某些单元格数
How to replace some cells number of .csv file if specific lines found in Linux
假设我有以下 file.csv 文件内容
"US","BANANA","123","100","0.5","ok"
"US","APPLE","456","201","0.1", "no"
"US","PIE","789","109","0.8","yes"
"US","APPLE","245","201","0.4","no"
我想搜索所有包含 APPLE 和 201 的行,然后将第 5 列的值替换为 0。因此,我的输出如下所示
"US","BANANA","123","100","0.5","ok"
"US","APPLE","456","201","0", "no"
"US","PIE","789","109","0.8","yes"
"US","APPLE","245","201","0","no"
我可以进行 grep 搜索
grep "APPLE" file.csv | grep 201
找出台词。但无法弄清楚如何修改原始文件中这些行的第 5 列值。
您可以为此使用 awk:
awk -F, '=="\"APPLE\"" { for (i=1;i<=NF;i++) { if ($i=="\"201\"") { gsub(,"\""substr(,2,length()-1)*1.10"\"",) } } }1' file.csv
将字段分隔符设置为 ,然后当第二个字段等于引号中的APPLE时,循环遍历每个字段并检查是否等于引号中的201。如果是,请使用 Awk 的 gsub 函数将引号中的第 5 个字段替换为 0。打印每一行,更改或使用简写 1
假设我有以下 file.csv 文件内容
"US","BANANA","123","100","0.5","ok"
"US","APPLE","456","201","0.1", "no"
"US","PIE","789","109","0.8","yes"
"US","APPLE","245","201","0.4","no"
我想搜索所有包含 APPLE 和 201 的行,然后将第 5 列的值替换为 0。因此,我的输出如下所示
"US","BANANA","123","100","0.5","ok"
"US","APPLE","456","201","0", "no"
"US","PIE","789","109","0.8","yes"
"US","APPLE","245","201","0","no"
我可以进行 grep 搜索
grep "APPLE" file.csv | grep 201
找出台词。但无法弄清楚如何修改原始文件中这些行的第 5 列值。
您可以为此使用 awk:
awk -F, '=="\"APPLE\"" { for (i=1;i<=NF;i++) { if ($i=="\"201\"") { gsub(,"\""substr(,2,length()-1)*1.10"\"",) } } }1' file.csv
将字段分隔符设置为 ,然后当第二个字段等于引号中的APPLE时,循环遍历每个字段并检查是否等于引号中的201。如果是,请使用 Awk 的 gsub 函数将引号中的第 5 个字段替换为 0。打印每一行,更改或使用简写 1