0

I am able to print and change data on a column or row in a csv file using awk command. But how can I change data at a particular column-row combination?

For example at 3rd column on 2nd row:

NAME,AGE,ID,SCHOOL
ABC,20,4545,DGDG
NRG,23,6767,BDBD
DGE.21,5858,FRFR

I want to change 6767 to 0000.

Can't figure out

2 Answers2

2

Match the third record (row; header is the first record, so you have to add 1) and edit the third field (column):

$ awk -F, -v OFS=, 'NR==3 {$3="0000"}1' data.txt
NAME,AGE,ID,SCHOOL
ABC,20,4545,DGDG
NRG,23,0000,BDBD
DGE.21,5858,FRFR
Discussian
  • 492
  • 3
  • 10
  • Thanks print is working fine : awk -F, 'NR==2{print $1}' file.csv but updation is not working : awk -F, 'NR==2{$1="ABCD"}' file.csv – Dibyajyoti Giri Apr 11 '23 at 12:53
  • 1
    You forgot `-vOFS=,`. It sets the field separator for outputting records. And `1` on the end is important as well, otherwise nothing will get printed. See: https://unix.stackexchange.com/questions/63891/what-is-the-meaning-of-1-at-the-end-of-an-awk-script – Discussian Apr 11 '23 at 12:59
  • Actually, the command is printing the expected result without -v0FS=, and 1. The issue is when I am trying to update the field. – Dibyajyoti Giri Apr 11 '23 at 13:06
  • Show the exact command you're using to update the field. – Discussian Apr 11 '23 at 13:12
  • awk -F, 'NR==2{$1=="0000"}' file.csv awk -F, -v OFS=, 'NR==2{$1=="0000"}' file.csv both not working – Dibyajyoti Giri Apr 11 '23 at 14:45
  • You forgot to add `1` at the end and used `==` in an assignment, where you have to use a single `=`. – Discussian Apr 11 '23 at 14:47
  • sorry am using "=" there. typo. and could you please explain why 1 is needed? I am trying to edit on 2nd row(count includes the header). – Dibyajyoti Giri Apr 11 '23 at 14:53
  • See the link I pasted earlier. Basically, it tells Awk to print each line it processes. – Discussian Apr 11 '23 at 15:00
  • This worked, thanks. Now I want to change 2 data; 1st and 2nd column of the 2nd row. When I am running the commands one after another (first for 1st column, second for 2nd column), I noticed the 1st change gets reverted after running the second change. Can I change both in one command? if yes, please suggest how. – Dibyajyoti Giri Apr 12 '23 at 14:14
  • `NR==2 {$1="foo"; $2="bar"}1` – Discussian Apr 12 '23 at 14:20
  • Thanks again Now I want the "Bar" to be entered as an argument like this. test.sh \"hello\". I want "hello" as a data in the csv with double quote. Currently I am using line this NR==2 {$1="echo $1"; $2="echo $"}1 , but something is not right. want to pass two arguments. – Dibyajyoti Giri Apr 18 '23 at 08:27
  • https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script/19075707#19075707 – Discussian Apr 18 '23 at 11:27
0

Try this:

 awk 'BEGIN{FS=OFS=","} NR==3{$3="0000"} 1' data.csv > data2.csv
protob
  • 3,317
  • 1
  • 8
  • 19