简体   繁体   中英

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!

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

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

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