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?

anubhava
  • 761,203
  • 64
  • 569
  • 643
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
  • 1
    Can something like this `echo VIN_oFDCAN8_8d836e25_In_data | sed 's/_In_data/_In_Moto_data/'` will work for your case? – Krishnom May 02 '19 at 09:48

3 Answers3

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.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 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 May 02 '19 at 10:16
  • @Bodo, thank you for letting know, added in my answer now. – RavinderSingh13 May 02 '19 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
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
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/'

Krishnom
  • 1,348
  • 12
  • 39