Replacing line of field seperated by delimiter

classic Classic list List threaded Threaded
8 messages Options
Reply | Threaded
Open this post in threaded view
|

Replacing line of field seperated by delimiter

Wayne
Hi, i read your sed tutorial and i found some of it useful for me. i wonder if i can use sed to replace a field with delimiters like a,b,c,d,e and i wish to replace e with f.



Reply | Threaded
Open this post in threaded view
|

Re: Replacing line of field seperated by delimiter

Guru
Administrator
I am not sure whether I got your question correctly. To just replace e with f:

echo "a,b,c,d,e" | sed 's/e/f/'



Reply | Threaded
Open this post in threaded view
|

Re: Replacing line of field seperated by delimiter

Wayne
sorry. i forgot to add 1 more field. a,b,c,d,e,e
if i wish to replace the 2nd e with f, how can i do it?

i have tried on my own using awk but i have the syntax error which says "awk: line 1: syntax error at or near =". can you point out my mistake? Many thanks.

$line is the line which i want to replace.

awk -F',' "NR==$line{$6=$newalpha}1" ofs=":" alpha.txt
Reply | Threaded
Open this post in threaded view
|

Re: Replacing line of field seperated by delimiter

Guru
Administrator
Try this way:

awk -F',' -v n="$line" -v na="$newalpha" 'NR==n{$6=na;}1' OFS=":" alpha.txt
Reply | Threaded
Open this post in threaded view
|

Re: Replacing line of field seperated by delimiter

Wayne
Thanks alot. i see it on my terminal but the value is not being update to my text file. is there something that i have missed out? Many Thanks.
Reply | Threaded
Open this post in threaded view
|

Re: Replacing line of field seperated by delimiter

Wayne
Sorry. I found the answer to it already. i pipe it to another alpha.txt file in another folder before moving it back to replace the alpha.txt. Thanks alot for your help.
Reply | Threaded
Open this post in threaded view
|

Re: Replacing line of field seperated by delimiter

Guru
Administrator
In reply to this post by Wayne
The file does not get updated. You have to re-direct the output to a file, and then rename it:


awk -F',' -v n="$line" -v na="$newalpha" 'NR==n{$6=na;}1' OFS=":" alpha.txt > f1
mv f1 alpha.txt
Reply | Threaded
Open this post in threaded view
|

Re: Replacing line of field seperated by delimiter

Wayne
This post was updated on .
Thank you. I did it the same way as your solution.