1

I have strings like below

VIN_oFDCAN8_8d836e25_In_data;
IPC_FD_1_oFDCAN8_8d836e25_In_data
BRAKE_FD_2_oFDCAN8_8d836e25_In_data

I want to insert _Moto in between as below

VIN_oFDCAN8_8d836e25_In_Moto_data
IPC_FD_1_oFDCAN8_8d836e25_In_Moto_data
BRAKE_FD_2_oFDCAN8_8d836e25_In_Moto_data

But when I used sed with capturing group as below

echo VIN_oFDCAN8_8d836e25_In_data | sed 's/_In_*\(_data\)/_Moto_\1/'

I get output as:

VIN_oFDCAN8_8d836e25_Moto__data

Can you please point me to right direction?

1
  • 1
    Can something like this echo VIN_oFDCAN8_8d836e25_In_data | sed 's/_In_data/_In_Moto_data/' will work for your case?
    – Krishnom
    Commented May 2, 2019 at 9:48

3 Answers 3

3

Though you could use simple substitution of IN string(considering that it is present only 1 time in your Input_file) but since your have asked specifically for capturing style in sed, you could try following then.

sed 's/\(.*_In\)\(.*\)/\1_Moto\2/g'  Input_file

Also above will add string _Moto to avoid adding 2 times _ after Moto confusion, Thanks to @Bodo for mentioning same in comments.

Issue with OP's attempt: Since you are NOT keeping _In_* in memory of sed so it is taking \(_data_\) only as first thing in memory, that is the reason it is not working, I have fixed it in above, we need to keep everything till _IN in memory too and then it will fly.

2
  • It might be worth mentioning an additional small issue. The modified script adds _Moto without a trailing _ to avoid the two _ in the example output VIN_oFDCAN8_8d836e25_Moto__data
    – Bodo
    Commented May 2, 2019 at 10:16
  • @Bodo, thank you for letting know, added in my answer now. Commented May 2, 2019 at 10:24
1
$ sed 's/_[^_]*$/_Moto&/' file
VIN_oFDCAN8_8d836e25_In_Moto_data
IPC_FD_1_oFDCAN8_8d836e25_In_Moto_data
BRAKE_FD_2_oFDCAN8_8d836e25_In_Moto_data
0

In your case, you can directly replace the matching string with below command

echo VIN_oFDCAN8_8d836e25_In_data | sed 's/_In_data/_In_Moto_data/'

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