1

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!

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. Is there anyway to overwrite to the same file without taking a copy?
If you have gnu-awk then use awk -i inplace -v id='uid_04' -v repl='ruby' 'BEGIN {FS=OFS=", "} $1 == id {$2 = repl} 1' file.csv
@SankaranKutty every Unix tool that has an option to enable "inplace" editing (gawk -i inplace, perl -i, ruby -i, sed -i, etc.) takes a copy of the file so - do you really care about taking a copy of the file or do you just not want to do it explicitly in your code with cmd file > tmp && mv tmp file and would prefer cmd -i file or cmd -i inplace file?
awk -v id1=$id -v repl='PASS' 'BEGIN {FS=OFS=","} ($1 == id1){$6 = repl} 1' $OUTPUT > tmp && mv tmp $OUTPUT made it work, thanks guys. :) @EdMorton - new to this, gawk is not present in the box, so i will go with this for time being. Thanks for the reply.
@anubhava Thank you Could you tell me what that 1 near file name does?
|
0

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

1 Comment

Sorry, its not working, sed: bad option in substitution expression

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.