基于条件的查找和替换csv文件字段中的值

时间:2019-09-26 06:19:48

标签: shell awk

我想根据第1列给出的条件在第5列和第6列中查找和替换值。如果第一列的值为2159,则如果第13列的值为13.512034,则应用13.49694替换第5列的值,并替换第6列中的值如果值为78.226233,则按78.22772。我尝试使用以下命令,但是它将第6列中的所有出现的78.226233替换为78.22772。我想要的是,它应该仅替换第1列中的2159值。

awk -F ',' -v OFS=',' '$1 ~ /^2159/ && $5=="13.512034"{$5="13.49694"}1 && $6=="78.226233"{$6="78.22772"}1' 14update1.csv > 14update2.csv

有什么方法可以更新同一文件中的更改? 对于awk和Shell脚本,我还很陌生,因此,如果这很容易解决,我深表歉意。

我拥有的数据文件类似于:

2159,KOLAR,SRINIVASAPURA,GAUNIPALLI (KODIPALLI) (GP),13.49694,78.22772,14-08-17,22,0
2159,KOLAR,SRINIVASAPURA,GAUNIPALLI (KODIPALLI) (GP),13.49694,78.22772,14-08-17,23,0
2159,KOLAR,SRINIVASAPURA,GAUNIPALLI (KODIPALLI) (GP),13.49694,78.22772,14-08-17,23,0
2159,KOLAR,SRINIVASAPURA,GAUNIPALLI (KODIPALLI) (GP),13.49694,78.22772,14-08-17,23,0
2159,KOLAR,SRINIVASAPURA,GAUNIPALLI (KODIPALLI) (GP),13.49694,78.22772,14-08-17,23,0
3358,KOLAR,SRINIVASAPURA,Gownipalli (GP),13.512034,78.22772,14-08-17,0,0
3358,KOLAR,SRINIVASAPURA,Gownipalli (GP),13.512034,78.22772,14-08-17,0,0
3358,KOLAR,SRINIVASAPURA,Gownipalli (GP),13.512034,78.22772,14-08-17,0,0
3358,KOLAR,SRINIVASAPURA,Gownipalli (GP),13.512034,78.22772,14-08-17,0,0
3317,KOLAR,SRINIVASAPURA,Hodali (GP),13.358552,78.269189,14-08-17,0,0
3317,KOLAR,SRINIVASAPURA,Hodali (GP),13.358552,78.269189,14-08-17,0,0
3317,KOLAR,SRINIVASAPURA,Hodali (GP),13.358552,78.269189,14-08-17,0,0
3317,KOLAR,SRINIVASAPURA,Hodali (GP),13.358552,78.269189,14-08-17,0,0
3317,KOLAR,SRINIVASAPURA,Hodali (GP),13.358552,78.269189,14-08-17,1,0
3317,KOLAR,SRINIVASAPURA,Hodali (GP),13.358552,78.269189,14-08-17,1,0
3317,KOLAR,SRINIVASAPURA,Hodali (GP),13.358552,78.269189,14-08-17,1,0
3317,KOLAR,SRINIVASAPURA,Hodali (GP),13.358552,78.269189,14-08-17,1,0

2 个答案:

答案 0 :(得分:2)

awk应该这样做:

cat file
2159,23,45,45,13.512034,78.226233

awk -F, -v OFS="," '$1==2159 && $5==13.512034 {$5="13.49694"} $1==2159 && $6==78.226233 {$6="78.22772"} 1' file
2159,23,45,45,13.49694,78.22772

$1 ~ /^2159/的开头而不是等于。 $1=2159$1~/^2159$/

答案 1 :(得分:1)

使用sub()

$ awk '
BEGIN {
    FS=OFS=","
}  
$1==2159 {                             # only one condition 
    sub(/^13\.512034$/,"13.49694",$5)   # or if($5=="13.512034") $5="13.49694"
    sub(/^78\.226233$/,"78.22772",$6)   # ditto
} 
1' file

输出:

2159,23,45,45,13.49694,78.22772