简体   繁体   中英

Replace a value for the nth column in a csv file with sed /awk/any linux tool

I want to replace the 28th column in a csv file from '2020-03-08' to '2020-03-08 00:00' . I have tried : gawk -i inplace -F"," '{sub($28,"&00:00"); print}' $filename gawk -i inplace -F"," '{sub($28,"&00:00"); print}' $filename . This misfires because $28 is a date which might even be empty , so it replaces any value in the file not specific 28th column .

Also, 2020-03-08 can be present anywhere in the csv file , it can get replaced instead of the 28th column . How can i resolve this ?

Eg of a line in csv file:

1057481434,e0e529d7-0942-44b1-b26d-794809edb113,2020-03-08 00:20:54+00,2020-03-07 13:50:28+00,fc7557d9-900b-4739-a678-79273dbbcaaf,android,indoor,stationary,100,1774,1774,105,336305e8-abfc-41b6-a07e-50c297c517bc,indoor,f,,,t,,,2020-03-07 13:50:27.539555+00,2020-03-07 13:50:27.539555+00,,31.6838,76.5255,1600,0,2020-03-08,0,,,0,0,0,,"31.6838125,76.52552",America/New_York,ASUS_X00TD,asus,asus,0.8.0,com.pepkit.ssg,83,e172ebc7-a301-4ed0-98a8-d1b852cc2235

You are taking the string in $28 and replacing it anywhere on the line. Try

{ $28 = $28 " 00:00" }1

or, if you insist on using sub ,

{ sub(/$/, " 00:00", $28) }1

Notice how the third argument indicates where to replace, instead of on the entire input line.

If you only want to replace when $28 is non-empty, make the action conditional.

$28 { $28 = $28 " 00:00" }1

The final 1 is a common shorthand for

{ print }

Recall that both the condition and the action are optional. If the condition is empty, the action is taken unconditionally. If the action is empty, the default action is to print the current input line. The lone 1 is a condition which is always true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM