search and replace string occurance in a specific column

9 views
Skip to first unread message

jabir m

unread,
Sep 4, 2014, 12:57:19 PM9/4/14
to unix-and-perl-...@googlegroups.com
Hi -
I am trying to write a code to search and replace the occurrence of a string in a specific column.
Can any one please help me to do this?
i/p

20120311~0568~12~ 12.34~231.45     
20120311~0808~12~ 11.34~568.45 
20120312~0568~12~ 10.34~161.45     

o/p required
20120311~0808~12~ 12.34~231.45     
20120311~0808~12~ 11.34~568.45
20120312~0808~12~ 10.34~161.45    

in the above example, i need to replace 568 to 808 in the second column.
I tried with sed and it is replacing 568 in all place.

thanks
Jabir

jabir m

unread,
Sep 4, 2014, 12:58:06 PM9/4/14
to unix-and-perl-...@googlegroups.com
the data is in a file and I am trying to do with shell scripting in Unix environment

jabir m

unread,
Sep 4, 2014, 2:28:30 PM9/4/14
to unix-and-perl-...@googlegroups.com
I found a solution by searching net and here is what i did

nawk -F'~'  '{gsub("568","808",$2)}1' filename


On Thursday, September 4, 2014 9:57:19 AM UTC-7, jabir m wrote:

Marek Borowiec

unread,
Sep 4, 2014, 4:46:04 PM9/4/14
to unix-and-perl-...@googlegroups.com
Awk certainly is more elegant, but depending on how stable the patterns in your file are, you could still use sed with regular expressions:

sed  -i 's/\(^[0-9]\+~\)[0-9]\+/\10808/g' <filename>

This would take your file, store first column (pattern of multiple numbers) from the beginning of line (^) plus the delimiter (~) into the first backreference, then find immediately following pattern of numbers and substitute those with your first column, or backreference \1, followed by 0808. Note the backslashes that denote non-literal interpretation of special characters for regex (plus signs and parentheses). This results in:

20120311~0808~12~ 12.34~231.45     
20120311~0808~12~ 11.34~568.45 
20120312~0808~12~ 10.34~161.45

Best,
Marek

 


--
You received this message because you are subscribed to the Google Groups "Unix and Perl for Biologists" group.
To unsubscribe from this group and stop receiving emails from it, send an email to unix-and-perl-for-bi...@googlegroups.com.
To post to this group, send email to unix-and-perl-...@googlegroups.com.
Visit this group at http://groups.google.com/group/unix-and-perl-for-biologists.
For more options, visit https://groups.google.com/d/optout.



--
Marek L. Borowiec
Ward Lab, 381 Briggs Hall
Department of Entomology
University of California, Davis
One Shields Avenue
Davis, CA 95616

https://sites.google.com/site/marekborowiecmyrmecologist/
Reply all
Reply to author
Forward
0 new messages