Sankaran Kutty
Sankaran Kutty

Reputation: 23

replace nth value of a csv line using sed in bash

I have some csv like below

uid_01, joe, yes, no 
uid_02, sam, yes, maybe
uid_03, c, ruth, yes, maybe
uid_04, **alan**, no, yes

I want to replace alan with ruby, uid will be unique here. I need to change depending on $position, any idea how to get that in sed?

Also I want to give both pattern and replacement value as arguments.

Tried something like this, but working only at last entry

sed -i '/^'$uid',/s/[^,]*$/'$returnvalue'/' $OUTPUT

Thanks in advance, please help!

Upvotes: 1

Views: 193

Answers (2)

potong
potong

Reputation: 58558

This might work for you (GNU sed):

id='uid_04' name='ruby' position=2
sed -i "/^$id,/s/[^,]*/ $name/$position" file

If the id is uid_04 replace the second field by ruby

Upvotes: 0

anubhava
anubhava

Reputation: 786081

awk suits it better:

awk -v id='uid_04' -v repl='ruby' 'BEGIN {FS=OFS=", "}
$1 == id {$2 = repl} 1' file.csv

uid_01, joe, yes, no
uid_02, sam, yes, maybe
uid_03, c, ruth, yes, maybe
uid_04, ruby, no, yes

Upvotes: 1

Related Questions