Issue
I have a file that has this :
cat textfile.csv
Name,Age,City
Jen,40,San Diego
Jen,,NYC
Bob,29,Miami,
,30,Boston
Jen,,NYC
Bob,21,Seattle
instead of using vim to manually do it .. is there a way I can use awk/sed to edit the 2nd Jen's age from ,, to whatever I want?
Also notice how there are 2 Jen,,NYC ... I want to be able to choose the 2nd Jen,,NYC (above the seattle one) and edit that one
Eventually this file will grow and there maybe more than 1 Bob/Jen so I want to be able to target the specific Jen I want and edit the field (whether that be name,age,city) if needed.
Solution
I would use GNU AWK
for this task following way, say you want set age of 2nd Jen,,NYC
to 35
and let textfile.csv
content be
Name,Age,City
Jen,40,San Diego
Jen,,NYC
Bob,29,Miami,
,30,Boston
Jen,,NYC
Bob,21,Seattle
then
awk -i inplace 'BEGIN{FS=OFS=","}$0=="Jen,,NYC"{cnt+=1;if(cnt==2){$2=35}}{print}' textfile.csv
will alter textfile.csv
content to
Name,Age,City
Jen,40,San Diego
Jen,,NYC
Bob,29,Miami,
,30,Boston
Jen,35,NYC
Bob,21,Seattle
Explanation: I inform GNU AWK
that both field separator (FS
) and output field separator (OFS
) is ,
. Then if currently processed line ($0
) is Jen,,NYC
I increase cnt
value by 1
. if
value of cnt
is equal to 2
I set 2nd field value to be 35
. For each line, change or not, I print
it. You might elect to first run without -i inplace
so GNU AWK
will output to standard output, check if it did give what you desire, then apply -i inplace
.
(tested in gawk 4.2.1)
Answered By - Daweo Answer Checked By - Mary Flores (WPSolving Volunteer)