![如果匹配特定关键字,则更改表中的多个列值](https://linux22.com/image/178085/%E5%A6%82%E6%9E%9C%E5%8C%B9%E9%85%8D%E7%89%B9%E5%AE%9A%E5%85%B3%E9%94%AE%E5%AD%97%EF%BC%8C%E5%88%99%E6%9B%B4%E6%94%B9%E8%A1%A8%E4%B8%AD%E7%9A%84%E5%A4%9A%E4%B8%AA%E5%88%97%E5%80%BC.png)
我有以下格式的数据:
38%,1,0,0
32%,400,376.61,94.1525
54%,400,197,49.25
22%,1,1,100
如果第二列等于 1,则将第二、第三和第四列更改为 NA
38%,NA,NA,NA
32%,400,376.61,94.1525
54%,400,197,49.25
22%,NA,NA,NA
我尝试先替换一列,但它不起作用:
awk -F, '$2==1 {$2="NA"}1' OFS=,
答案1
要修改多列,请用分号分隔分配:
$ awk -F, '$2==1 {$2="NA"; $3="NA"; $4="NA"}1' OFS=, file
38%,NA,NA,NA
32%,400,376.61,94.1525
54%,400,197,49.25
22%,NA,NA,NA
答案2
您可以尝试使用以下命令
awk -F "," '$2 == "1" {$2=$3=$4="NA"}1' file
输出
38% NA NA NA
32%,400,376.61,94.1525
54%,400,197,49.25
22% NA NA NA
Python
#!/usr/bin/python
k=open('file','r')
for i in k:
j=i.split(",")
if (j[1] == "1"):
j[1]=j[2]=j[3]="NA"
print ",".join(j)
else:
print i.strip()
输出
38%,NA,NA,NA
32%,400,376.61,94.1525
54%,400,197,49.25
22%,NA,NA,NA