Q:

String replacement in a text file

i have a text file "out" like below,
r 19.568805475 _16_ RTR  --- 189 cbr 532 [13a 10 c 800] [energy 1.095631 ei 0.000 es 0.000 et 0.552 er 1.352] ------- [0:2 17:0 23 16] [189] 8 0
f 19.568805475 _16_ RTR  --- 189 cbr 532 [13a 10 c 800] [energy 1.095631 ei 0.000 es 0.000 et 0.552 er 1.352] ------- [0:2 17:0 22 8] [189] 8 0
D 19.568805475 _16_ IFQ  ARP 190 cbr 532 [13a 10 10 800] [energy 1.095631 ei 0.000 es 0.000 et 0.552 er 1.352] ------- [0:2 17:0 24 8] [190] 6 0
r 19.569095175 _12_ MAC  --- 0 ACK 38 [0 c 0 0] [energy 0.841123 ei 0.000 es 0.000 et 0.316 er 1.843] 
s 19.569306186 _2_ MAC  --- 0 undefined 106 [0 ffffffff 2 800] [energy 0.889732 ei 0.000 es 0.000 et 0.633 er 1.477] ------- [2:255 -1:255 25 0] 

now i want to search a line with word "cbr" , if the same line start with "^D",  i have to replace "^D" by "r".
for example,
D 19.568805475 _16_ RTR  --- 189 cbr 532 [13a 10 c 800] [energy 1.095631 ei 0.000 es 0.000 et 0.552 er 1.352] 

the above line has word "cbr", and the line start with "D". here i have to change "D" by "r"
Can any one help me to do this?
thanks

A:

Let's use sed for this:
sed '/cbr/s/^D/r/' file
      ^^^ ^ ^^ ^
       |  | |  |
       |  | |  replace with "r"
       |  | starting with "D"
       |  replace
     string containing "cbr"

As per the basic sed s/findsomething/andreplace/' file syntax.
It returns:
r 19.568805475 _16_ RTR  --- 189 cbr 532 [13a 10 c 800] [energy 1.095631 ei 0.000 es 0.000 et 0.552 er 1.352] ------- [0:2 17:0 23 16] [189] 8 0
f 19.568805475 _16_ RTR  --- 189 cbr 532 [13a 10 c 800] [energy 1.095631 ei 0.000 es 0.000 et 0.552 er 1.352] ------- [0:2 17:0 22 8] [189] 8 0
r 19.568805475 _16_ IFQ  ARP 190 cbr 532 [13a 10 10 800] [energy 1.095631 ei 0.000 es 0.000 et 0.552 er 1.352] ------- [0:2 17:0 24 8] [190] 6 0
r 19.569095175 _12_ MAC  --- 0 ACK 38 [0 c 0 0] [energy 0.841123 ei 0.000 es 0.000 et 0.316 er 1.843] 
s 19.569306186 _2_ MAC  --- 0 undefined 106 [0 ffffffff 2 800] [energy 0.889732 ei 0.000 es 0.000 et 0.633 er 1.477] ------- [2:255 -1:255 25 0] 

