Regular expression to replace a word with another word on the same line unix

advertisements

Let A,B,C,D are the words

Input File :

..
A/B/C/D
W/B/C/Z
L/B/C/O
..

Output file:

..
A/B/C/A
W/B/C/W
L/B/C/L
..

Replace the word D with word A one the same line, only if /B/C/ delimiter present in the line and like wise for the other lines

Any sed/awk/perl oneliner to accomplish that


You can do:

sed -re 's/^([^/]*)(\/B\/C\/)([^/]*)$/\1\2\1/' file

Demo:

$ cat file
A/B/C/D
W/B/C/Z
L/B/C/O

$ sed -re 's/^([^/]*)(\/B\/C\/)([^/]*)$/\1\2\1/' file
A/B/C/A
W/B/C/W
L/B/C/L