使用sed命令捕获组

时间:2019-05-21 09:45:45

标签: sed

我有类似下面的字符串

 _c_VehCfg1_oCAN00_f276589c_In_Int_buf *pVehCfg1_oCAN00_f276589c_In_IntBuf = (_c_VehCfg1_oCAN00_f276589c_In_Int_buf *)can_Msg_tmp_buffer;  

我想将can_Msg_tmp_buffer替换为ptr,如下所示:

_c_VehCfg1_oCAN00_f276589c_In_Int_buf *pVehCfg1_oCAN00_f276589c_In_IntBuf = (_c_VehCfg1_oCAN00_f276589c_In_Int_buf *)ptr;

我尝试了以下sed

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'

仍然没有得到预期的结果,相反sed的输出与输入相同。

问题是我也有下面的字符串

_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;

我只想替换type_Int_buf结尾的位置,而不是_Moto_buf

2 个答案:

答案 0 :(得分:1)

使用正则表达式匹配单个单词并从中获取捕获的单词非常费时费力。一种方法是使用保证发生的字符串的已知部分。

对于您的情况,我们使用字符串_In_IntBufcan_Msg_tmp_buffer;来唯一地标识那些线型并进行替换

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

答案 1 :(得分:1)

如果您对awk没问题,请尝试以下操作。

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

如果要将输出保存到Input_file本身,请在上面的代码中附加> temp_file && mv temp_file Input_file