fibar
fibar

Reputation: 179

Replace nth string from each line starting from the end

I have lines that have a variable number of underscores. I need to replace the 3rd underscore starting from the end of the line. Is there a sed, awk or any other oneliner option?

Example:

>ABC_BBB_VVV_BBB_NNN
>ABC_BBB_FFF_VVV_BBB_NNN

should turn into

>ABC_BBB=VVV_BBB_NNN
>ABC_BBB_FFF=VVV_BBB_NNN

Upvotes: 1

Views: 181

Answers (4)

Claes Wikner
Claes Wikner

Reputation: 1517

awk '{sub(/_VVV/,"=VVV")}1' file

>ABC_BBB=VVV_BBB_NNN
>ABC_BBB_FFF=VVV_BBB_NNN

Upvotes: 0

John1024
John1024

Reputation: 113994

This looks for the third _ from the end and replaces it with a =:

$ sed -E 's/_([^_]*_[^_]*_[^_]*)$/=\1/' input
ABC_BBB=VVV_BBB_NNN    
ABC_BBB_FFF=VVV_BBB_NNN

This can be slightly shortened to:

sed -E 's/_([^_]*(_[^_]*){2})$/=\1/' input

The above is for n=3. For other n, just replace the 2 with n-1.

Upvotes: 2

Jeff Y
Jeff Y

Reputation: 2466

Or awk:

awk -F_ '{for(i=1;i<NF;++i)printf("%s%c",$i,i==NF-3?"=":"_");printf("%s\n",$NF)}'

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204638

Assuming you want to be able to adapt the solution to 2 or 4 or any other number of underscores from either end and using GNU awk for gensub():

$ awk -F_ '{$0=gensub(FS,"=",NF-3)}1' file
ABC_BBB=VVV_BBB_NNN
ABC_BBB_FFF=VVV_BBB_NNN

$ awk -F_ '{$0=gensub(FS,"=",NF-2)}1' file
ABC_BBB_VVV=BBB_NNN
ABC_BBB_FFF_VVV=BBB_NNN

$ awk -F_ '{$0=gensub(FS,"=",NF-4)}1' file
ABC=BBB_VVV_BBB_NNN
ABC_BBB=FFF_VVV_BBB_NNN

Upvotes: 0

Related Questions