0

I have strings like below

 _c_VehCfg1_oCAN00_f276589c_In_Int_buf *pVehCfg1_oCAN00_f276589c_In_IntBuf = (_c_VehCfg1_oCAN00_f276589c_In_Int_buf *)can_Msg_tmp_buffer;  

I want replace can_Msg_tmp_buffer with ptr as below

_c_VehCfg1_oCAN00_f276589c_In_Int_buf *pVehCfg1_oCAN00_f276589c_In_IntBuf = (_c_VehCfg1_oCAN00_f276589c_In_Int_buf *)ptr;

I have tried sed as below

echo  "_c_VehCfg1_oCAN00_f276589c_In_Int_buf *pVehCfg1_oCAN00_f276589c_In_IntBuf = (_c_VehCfg1_oCAN00_f276589c_In_Int_buf *)can_Msg_tmp_buffer;" | sed  's/\(_C_[[:alnum:]_]*IntBuf = [[:alnum:]_]*\)can_Msg_tmp_buffer/1\ptr/g'

Still I'm not getting expected result instead sed output is same as input.

The problem is I have strings like below also

_c_GW_C4_oCAN00_f276589c_In_Moto_buf *pGW_C4_oCAN00_f276589c_In_MotoBuf = (_c_GW_C4_oCAN00_f276589c_In_Moto_buf *)can_Msg_tmp_buffer;

I only want to replace where type is ending with _Int_buf not _Moto_buf.

1
  • 1
    I'm not sure why a close vote was registered against this question with reason Questions seeking debugging help ("why isn't this code working?"). The Q clearly has an attempt made (need to scroll through to see the sed command) and a valid i/p and an expected o/p provided
    – Inian
    Commented May 21, 2019 at 10:10

2 Answers 2

1

It gets extremely convoluted to match individual words with a regex and get a captured group out of it. One way would be to work with known parts of the string which are guaranteed to occur.

For your case, using the strings _In_IntBuf and can_Msg_tmp_buffer; we try to uniquely identify those pattern of lines and do the substitution

sed  's/\(.*\)_In_IntBuf = \(.*\)can_Msg_tmp_buffer;/\1_In_IntBuf = \2ptr;/'
0
1

In case you are ok with awk try following.

awk '/_In_IntBuf =/{sub(/can_Msg_tmp_buffer/,"ptr")} 1' Input_file

In case you want to save output into Input_file itself append > temp_file && mv temp_file Input_file in above code.

1
  • 1
    Its ok I only needed one working solution, as I'm working with huge C code sed command provided in above answer helped me. Commented May 21, 2019 at 10:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.